-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathis_graph_bipartite.cpp
38 lines (34 loc) · 1.02 KB
/
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
class Solution {
bool checkIsBipartite(vector<vector<int>> &graph, vector<int> &color, int &src) {
queue<int> Q;
color[src] = 1;
Q.push(src);
while(!Q.empty()) {
auto node = Q.front();
Q.pop();
for(auto &neighbor : graph[node]) {
if(color[neighbor] == -1) { //uncolored
color[neighbor] = 1 - color[node];
Q.push(neighbor);
}
else if(color[neighbor] == color[node]) { //colored but isSameAsParent?
return false;
}
}
}
return true;
}
public:
bool isBipartite(vector<vector<int>>& graph) {
int V = graph.size();
vector<int> color(V, -1);
for(int i = 0; i < V; i++) {
if(color[i] == -1) {
if(!checkIsBipartite(graph, color, i)) {
return false;
}
}
}
return true;
}
};