Skip to content

Commit 2acab96

Browse files
Create 0785-is-graph-bipartite.java
1 parent 8eea089 commit 2acab96

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

java/0785-is-graph-bipartite.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
public boolean isBipartite(int[][] graph) {
3+
int[] color = new int[graph.length]; // 1 for one color , -1 for second color and 0 for not visited.
4+
5+
for(int i = 0; i < graph.length; i++){
6+
if(color[i] != 0){
7+
continue;
8+
}
9+
10+
Queue<Integer> q = new LinkedList<>();
11+
q.add(i);
12+
color[i] = 1;
13+
14+
while(!q.isEmpty()){
15+
int curr = q.poll();
16+
17+
for(int n : graph[curr]){
18+
if(color[n] == 0){
19+
color[n] = -1 * color[curr];
20+
q.add(n);
21+
}
22+
if(color[n] == color[curr])
23+
return false;
24+
}
25+
}
26+
}
27+
return true;
28+
}
29+
}

0 commit comments

Comments
 (0)