-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBipartiteChecker.java
51 lines (41 loc) · 1.15 KB
/
BipartiteChecker.java
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
package org.sean.graph;
/***
* 785. Is Graph Bipartite?
*/
public class BipartiteChecker {
private boolean[] visited;
private boolean[] colored;
private boolean bipartite;
private boolean finished;
private void dfs(int[][] graph, int pos) {
if (!finished && !visited[pos]) {
visited[pos] = true;
for (int v : graph[pos]) {
if (!visited[v]) {
colored[v] = !colored[pos];
dfs(graph, v);
} else {
if (colored[v] == colored[pos]) {
finished = true;
bipartite = false;
}
}
}
}
}
public boolean isBipartite(int[][] graph) {
int vertexCnt = graph.length;
visited = new boolean[vertexCnt];
colored = new boolean[vertexCnt];
bipartite = true;
finished = false;
for (int i = 0; i < graph.length; i++) {
if (finished)
break;
if (!visited[i]) {
dfs(graph, i);
}
}
return bipartite;
}
}