forked from ex01tus/leetcode-grind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPossibleBipartition.java
More file actions
63 lines (51 loc) · 1.93 KB
/
PossibleBipartition.java
File metadata and controls
63 lines (51 loc) · 1.93 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
package graph;
import java.util.*;
/**
* Description: https://leetcode.com/problems/possible-bipartition
* Difficulty: Medium
* Time complexity: O(n)
* Space complexity: O(n)
*/
public class PossibleBipartition {
private static final int RED = 0;
private static final int BLUE = 1;
private static final int UNDEFINED = -1;
public boolean possibleBipartition(int n, int[][] dislikes) {
Map<Integer, List<Integer>> adjList = buildAdjList(dislikes);
int[] colors = new int[n + 1];
Arrays.fill(colors, UNDEFINED);
for (int i = 1; i <= n; i++) {
if (colors[i] == UNDEFINED && !isBipartite(i, adjList, colors)) {
return false;
}
}
return true;
}
private boolean isBipartite(int start, Map<Integer, List<Integer>> adjList, int[] colors) {
Queue<Integer> planned = new LinkedList<>();
planned.offer(start);
colors[start] = RED;
while (!planned.isEmpty()) {
int current = planned.poll();
for (int neighbor : adjList.getOrDefault(current, List.of())) {
if (colors[neighbor] == UNDEFINED) {
// color nodes red-blue-red-blue-...
colors[neighbor] = (colors[current] + 1) % 2;
planned.offer(neighbor);
} else if (colors[neighbor] == colors[current]) {
// if colors of neighbors match – graph is not bipartile
return false;
}
}
}
return true;
}
private Map<Integer, List<Integer>> buildAdjList(int[][] edges) {
Map<Integer, List<Integer>> adjList = new HashMap<>();
for (int[] edge : edges) {
adjList.computeIfAbsent(edge[0], __ -> new ArrayList<>()).add(edge[1]);
adjList.computeIfAbsent(edge[1], __ -> new ArrayList<>()).add(edge[0]);
}
return adjList;
}
}