Skip to content

Commit 27b9397

Browse files
authored
Create Possible Bipartition.java
1 parent a854e63 commit 27b9397

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Medium/Possible Bipartition.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public boolean possibleBipartition(int n, int[][] dislikes) {
3+
Map<Integer, List<Integer>> map = new HashMap<>();
4+
for (int[] dislike : dislikes) {
5+
map.computeIfAbsent(dislike[0], k -> new ArrayList<>()).add(dislike[1]);
6+
map.computeIfAbsent(dislike[1], k -> new ArrayList<>()).add(dislike[0]);
7+
}
8+
int[] color = new int[n + 1];
9+
Arrays.fill(color, -1);
10+
for (int i = 1; i <= n; i++) {
11+
if (color[i] == -1) {
12+
if (!bfs(i, map, color)) {
13+
return false;
14+
}
15+
}
16+
}
17+
return true;
18+
}
19+
20+
private boolean bfs(int node, Map<Integer, List<Integer>> map, int[] color) {
21+
Queue<Integer> queue = new LinkedList<>();
22+
queue.add(node);
23+
color[node] = 0;
24+
while (!queue.isEmpty()) {
25+
int removed = queue.remove();
26+
for (Integer neighbor : map.getOrDefault(removed, new ArrayList<>())) {
27+
if (color[neighbor] == color[removed]) {
28+
return false;
29+
}
30+
if (color[neighbor] == -1) {
31+
color[neighbor] = 1 - color[removed];
32+
queue.add(neighbor);
33+
}
34+
}
35+
}
36+
return true;
37+
}
38+
}

0 commit comments

Comments
 (0)