-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphBiColoringBFS.cpp
More file actions
101 lines (80 loc) · 2.15 KB
/
GraphBiColoringBFS.cpp
File metadata and controls
101 lines (80 loc) · 2.15 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/// UVa OJ - 10004
#include <bits/stdc++.h>
using namespace std;
#define WHITE 0
#define RED 1
#define BLUE 2
vector<vector<int> >adj;
vector<int>color;
queue<int>Q;
bool BiColorable(int source, int nodes);
void clearQ();
int main()
{
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
int n, L, i, j, u, v;
while (scanf("%d", &n) && n != 0) {
scanf("%d", &L);
adj.assign(n, vector<int>());
for (i = 1; i <= L; i++) {
scanf("%d%d", &u, &v);
adj[u].push_back(v);
adj[v].push_back(u);
}
/*for (i = 0; i < n; i++) {
printf("%d -> ", i);
for (j = 0; j < adj[i].size(); j++) {
printf("%d ", adj[i][j]);
}
printf("\n");
}*/
bool possible = BiColorable(0, n);
if (possible) {
printf("BICOLORABLE.\n");
}
else {
printf("NOT BICOLORABLE.\n");
}
}
return 0;
}
bool BiColorable(int source, int nodes)
{
int u, v, i;
color.assign(nodes, WHITE); /// Setting all nodes' color as WHITE initially
clearQ(); /// As, Q is global variable, it must be cleared before using
Q.push(source); /// At first, pushing source node into Q
color[source] = RED; /// Source is colored RED
while (!Q.empty()) {
u = Q.front();
Q.pop();
for (i = 0; i < adj[u].size(); i++) {
/// v will have the i-th adjacent node of u
v = adj[u][i];
/// If v is not colored, color it
if (color[v] == WHITE) {
if (color[u] == RED) {
color[v] = BLUE;
}
else {
color[v] = RED;
}
/// After coloring, push v into Q
Q.push(v);
}
/// We found that u and v are adjacent nodes
/// So, if their color is same, given graph is not bi-colorable
if (color[u] == color[v]) {
return false;
}
}
}
return true;
}
void clearQ()
{
while (!Q.empty()) {
Q.pop();
}
}