Skip to content

Commit b51c914

Browse files
authored
Merge pull request #168 from somya51p/solis
isGraphBipartite algorithm added
2 parents 5fca45c + 6edd702 commit b51c914

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/* ' Is Graph Bipartite ' problem from Leetcode
2+
3+
A graph is bipartite if the nodes can be partitioned into two independent sets A and B
4+
such that every edge in the graph connects a node in set A and a node in set B.
5+
6+
The main function is predefined. Here is the code to the question.
7+
*/
8+
9+
10+
class Solution {
11+
public:
12+
13+
vector<int> color;
14+
bool dfs(int node, vector<vector<int>> &graph){
15+
for(auto child: graph[node]){
16+
if(color[child] != -1){
17+
if(color[child] == color[node])
18+
return false;
19+
continue;
20+
}
21+
color[child] = (color[node] + 1)%2;
22+
if(!dfs(child, graph))
23+
return false;
24+
}
25+
return true;
26+
}
27+
28+
bool isBipartite(vector<vector<int>>& graph) {
29+
int n = graph.size();
30+
color = vector<int> (n, -1);
31+
for(int node=0; node<n; node++){
32+
if(color[node]==-1){
33+
color[node] = 0;
34+
if(!dfs(node, graph)) return false;
35+
}
36+
}
37+
return true;
38+
}
39+
};
40+
41+
/*
42+
Input: graph = [[1,2,3],[0,2],[0,1,3],[0,2]]
43+
Output: false
44+
*/

0 commit comments

Comments
 (0)