[BOJ] 1707번 이분 그래프 - C++

"DFS와 BFS"

Posted by Yongmin on July 24, 2021

문제

이분 그래프

풀이

DFS, BFS를 이용한 문제이며, 이분 그래프에 대해서 알게된 문제이다. 이분 그래프는 연결된 점들이 각각 다른 색깔로 이루어진 그래프를 의미한다. 코드상, 계속해서 방문하며 색ㄱ랑르 번갈아가면서 입력을 해준다. 그 이후 확인작업을 통해 색깔이 같은 지점이 있다면 false, 그렇지 않다면 true를 출력하게 하여 이분 그래프인지 확인한다.

소스 코드

```c++ #include

#include

#include

using namespace std;

const int MAX = 20000 + 1;

int K, V, E;

vector graph[MAX];

int nodeColor[MAX];

//color: 0 아직 방문 X, 1, 2는 각각 색깔

void DFS(int nodeNum, int color)

{

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    nodeColor[nodeNum] = color;

 

    for (int i = 0; i < graph[nodeNum].size(); i++)

    {

             int next = graph[nodeNum][i];

             if (!nodeColor[next])

                     DFS(next, 3 - color);

    }

}

//서로 연결된 노드끼리 같은 색깔이면 이분 그래프 X

bool isBipartiteGraph(void)

{

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    for (int i = 1; i <= V; i++)

             for (int j = 0; j < graph[i].size(); j++)

             {

                     int next = graph[i][j];

                     if (nodeColor[i] == nodeColor[next])

                             return false;

             }

    return true;

}

int main(void)

{

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
    cin >> K;

   

    for (int i = 0; i < K; i++)

    {

             for (int j = 1; j < MAX; j++)

                     graph[j].clear();

             memset(nodeColor, 0, sizeof(nodeColor));

 

             cin >> V >> E;

 

             for (int j = 0; j < E; j++)

             {

                     int node1, node2;

                     cin >> node1 >> node2;

 

                     graph[node1].push_back(node2);

                     graph[node2].push_back(node1);

             }

 

             for (int j = 1; j <= V; j++)

                     if (nodeColor[j] == 0)

                             DFS(j, 1); //1번 색깔부터 시작

 

             if (isBipartiteGraph())

                     cout << "YES" << endl;

             else

                     cout << "NO" << endl;

    }

    return 0;

}

//출처: https://jaimemin.tistory.com/648 [꾸준함]```



# # #