-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFlowerPlantingWithNoAdjacent.java
More file actions
76 lines (62 loc) · 2.39 KB
/
FlowerPlantingWithNoAdjacent.java
File metadata and controls
76 lines (62 loc) · 2.39 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
64
65
66
67
68
69
70
71
72
73
74
75
76
package graph;
import java.util.*;
/**
* Description: https://leetcode.com/problems/flower-planting-with-no-adjacent
* Difficulty: Medium
* Time complexity: O(n)
* Space complexity: O(n)
*/
public class FlowerPlantingWithNoAdjacent {
public int[] gardenNoAdjViaBFS(int n, int[][] paths) {
Map<Integer, List<Integer>> adjList = buildAdjList(paths);
int[] colors = new int[n];
for (int garden = 0; garden < n; garden++) {
if (colors[garden] == 0) {
bfs(adjList, colors, garden);
}
}
return colors;
}
private void bfs(Map<Integer, List<Integer>> adjList, int[] colors, int start) {
Queue<Integer> planned = new LinkedList<>();
planned.offer(start);
colors[start] = 1;
while (!planned.isEmpty()) {
int current = planned.poll();
for (int neighbor : adjList.getOrDefault(current, List.of())) {
if (colors[neighbor] == 0) {
// colors are 1-indexed: (colors[current] - 1 + 1) % 4 + 1 = colors[current] % 4 + 1
colors[neighbor] = colors[current] % 4 + 1;
planned.offer(neighbor);
} else if (colors[neighbor] == colors[current]) {
colors[neighbor] = colors[current] % 4 + 1;
}
}
}
}
public int[] gardenNoAdjViaGreedyAlgo(int n, int[][] paths) {
Map<Integer, List<Integer>> adjList = buildAdjList(paths);
int[] colors = new int[n];
for (int garden = 0; garden < n; garden++) {
Set<Integer> usedColors = new HashSet<>();
for (int neighbor : adjList.getOrDefault(garden, List.of())) {
usedColors.add(colors[neighbor]);
}
for (int color = 1; color <= 4; color++) {
if (!usedColors.contains(color)) {
colors[garden] = color;
break;
}
}
}
return colors;
}
private Map<Integer, List<Integer>> buildAdjList(int[][] paths) {
Map<Integer, List<Integer>> adjList = new HashMap<>();
for (int[] path : paths) {
adjList.computeIfAbsent(path[0] - 1, __ -> new ArrayList<>()).add(path[1] - 1);
adjList.computeIfAbsent(path[1] - 1, __ -> new ArrayList<>()).add(path[0] - 1);
}
return adjList;
}
}