-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path785. Is Graph Bipartite.cpp
68 lines (68 loc) · 2.3 KB
/
785. Is Graph Bipartite.cpp
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
class Solution {
public:
bool isBipartite1(vector<vector<int>>& graph) {
bool curr = false;
int n = graph.size();
vector<int> visited(n,false);
vector<int> colour(n,false);
for(int i=0;i<n;++i)
{
if(visited[i]) continue;
queue<int> q;
q.push(i);
queue<int> p;
while(!q.empty())
{
int k = q.front();
q.pop();
visited[k] = true;
colour[k] = curr;
for(auto t:graph[k])
{
if(visited[t] && colour[t] == curr)
return false;
else if(!visited[t])
p.push(t);
}
if(q.empty())
{
swap(p,q);
curr = !curr;
}
}
}
return true;
}
bool isBipartite(vector<vector<int>>& graph) {
int n = graph.size();
vector<int> colors(n, 0);
queue<int> q;
for (int i = 0; i < n; i++) {
if (colors[i]) continue;
colors[i] = 1;
q.push(i);
while (!q.empty()) {
int temp = q.front();
for (auto neighbor : graph[temp]) {
// Color neighbor with opposite color
if (!colors[neighbor]){
colors[neighbor] = -colors[temp];
q.push(neighbor);
}
// If the neighbor has the same color - can't bipartite.
else if (colors[neighbor] == colors[temp])
return false;
}
q.pop();
}
}
return true;
}
};