-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph_biparate.cpp
More file actions
62 lines (55 loc) · 1.37 KB
/
graph_biparate.cpp
File metadata and controls
62 lines (55 loc) · 1.37 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
vector<vector<ll>> adj;
vector<ll> color; // 0: no color, 1: color1, 2: color2
ll one = 0, two = 0;
bool isBipartite = true;
bool bfs(ll u)
{
color[u] = 1;
one++;
queue<ll> q;
q.push(u);
while (!q.empty())
{
int x = q.front();
q.pop();
for (auto &v : adj[x])
{
if (color[v] == 0)
{
// Assign alternate color
color[v] = 3 - color[x];
if (color[v] == 1)
one++;
else
two++;
q.push(v);
}
else if (color[v] == color[x])
{
// Same color adjacent nodes - not bipartite
isBipartite = false;
return false;
}
}
}
return true;
}
// Usage for entire graph (handles disconnected components)
void checkBipartite(ll n) {
color.assign(n, 0);
isBipartite = true;
one = 0; two = 0;
for (ll i = 0; i < n; i++) {
if (color[i] == 0) {
if (!bfs(i)) {
cout << "Graph is NOT bipartite!" << endl;
return;
}
}
}
if (isBipartite) {
cout << "Graph is bipartite" << endl;
cout << "Color 1 nodes: " << one << endl;
cout << "Color 2 nodes: " << two << endl;
}
}