-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path785. Is Graph Bipartite BFS.cpp
More file actions
38 lines (35 loc) · 1022 Bytes
/
785. Is Graph Bipartite BFS.cpp
File metadata and controls
38 lines (35 loc) · 1022 Bytes
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
/*
Problem Link: https://leetcode.com/problems/is-graph-bipartite/
Time: 81 ms (Beats 7.17%), Space: 13.7 MB (Beats 28.53%)
*/
class Solution {
private:
bool bfsCheck(int start, vector<int>& color, int col, vector<vector<int>>& graph){
queue<int> q;
q.push(start);
color[start]=0;
while(!q.empty()){
int node= q.front();
q.pop();
for(auto adjNode: graph[node]){
if(color[adjNode]==-1){
color[adjNode]= !color[node];
q.push(adjNode);
}
else if(color[adjNode]==color[node]) 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(bfsCheck(i, color, 0, graph)==false) return false;
}
}
return true;
}
};