Skip to content

Commit 025813b

Browse files
committed
Add Java solution for day27: Possible Bipartition
1 parent 5b056a2 commit 025813b

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import java.util.HashMap;
2+
3+
class Solution {
4+
public boolean possibleBipartition(int N, int[][] dislikes) {
5+
/**
6+
* Build a graph, try to color each node
7+
* 0, If the node hasn't been colored, => color to 1
8+
* 1, color its dislikes nodes to - color => color to -1
9+
* 2, conflct return false
10+
*/
11+
12+
Map<Integer, Set<Integer>> g = new HashMap<>();
13+
14+
// build graph
15+
for (int[] d : dislikes) {
16+
int a = d[0];
17+
int b = d[1];
18+
g.putIfAbsent(a, new HashSet<Integer>());
19+
g.putIfAbsent(b, new HashSet<Integer>());
20+
g.get(a).add(b);
21+
g.get(b).add(a);
22+
}
23+
24+
int[] colors = new int[N + 1];
25+
for (int i = 1; i <= N; i++) {
26+
// the node is not colored and there is a conflict
27+
if (colors[i] == 0 && !dfs(colors, 1, i, g)) return false;
28+
}
29+
30+
return true;
31+
}
32+
33+
private boolean dfs (int[] colors, int color, int node, Map<Integer, Set<Integer>> g) {
34+
// The node is already colored
35+
if (colors[node] != 0) {
36+
return colors[node] == color;
37+
}
38+
39+
colors[node] = color;
40+
if (g.get(node) == null) return true;
41+
for (int next : g.get(node)) {
42+
if (!dfs(colors, -color, next, g)) return false;
43+
}
44+
45+
return true;
46+
}
47+
}

0 commit comments

Comments
 (0)