|
| 1 | +package graph; |
| 2 | + |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +/** |
| 6 | + * Description: https://leetcode.com/problems/flower-planting-with-no-adjacent |
| 7 | + * Difficulty: Medium |
| 8 | + * Time complexity: O(n) |
| 9 | + * Space complexity: O(n) |
| 10 | + */ |
| 11 | +public class FlowerPlantingWithNoAdjacent { |
| 12 | + |
| 13 | + public int[] gardenNoAdj(int n, int[][] paths) { |
| 14 | + Map<Integer, List<Integer>> adjList = buildAdjList(paths); |
| 15 | + |
| 16 | + int[] colors = new int[n]; |
| 17 | + for (int garden = 0; garden < n; garden++) { |
| 18 | + if (colors[garden] == 0) { |
| 19 | + bfs(adjList, colors, garden); |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + return colors; |
| 24 | + } |
| 25 | + |
| 26 | + private void bfs(Map<Integer, List<Integer>> adjList, int[] colors, int start) { |
| 27 | + Queue<Integer> planned = new LinkedList<>(); |
| 28 | + planned.offer(start); |
| 29 | + colors[start] = 1; |
| 30 | + |
| 31 | + while (!planned.isEmpty()) { |
| 32 | + int current = planned.poll(); |
| 33 | + |
| 34 | + for (int neighbor : adjList.getOrDefault(current, List.of())) { |
| 35 | + if (colors[neighbor] == 0) { |
| 36 | + // colors are 1-indexed: (colors[current] - 1 + 1) % 4 + 1 = colors[current] % 4 + 1 |
| 37 | + colors[neighbor] = colors[current] % 4 + 1; |
| 38 | + planned.offer(neighbor); |
| 39 | + } else if (colors[neighbor] == colors[current]) { |
| 40 | + colors[neighbor] = colors[current] % 4 + 1; |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + public int[] gardenNoAdjViaGreedyAlgo(int n, int[][] paths) { |
| 47 | + Map<Integer, List<Integer>> adjList = buildAdjList(paths); |
| 48 | + |
| 49 | + int[] colors = new int[n]; |
| 50 | + for (int garden = 0; garden < n; garden++) { |
| 51 | + Set<Integer> usedColors = new HashSet<>(); |
| 52 | + for (int neighbor : adjList.getOrDefault(garden, List.of())) { |
| 53 | + usedColors.add(colors[neighbor]); |
| 54 | + } |
| 55 | + |
| 56 | + for (int color = 1; color <= 4; color++) { |
| 57 | + if (!usedColors.contains(color)) { |
| 58 | + colors[garden] = color; |
| 59 | + break; |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return colors; |
| 65 | + } |
| 66 | + |
| 67 | + private Map<Integer, List<Integer>> buildAdjList(int[][] paths) { |
| 68 | + Map<Integer, List<Integer>> adjList = new HashMap<>(); |
| 69 | + for (int[] path : paths) { |
| 70 | + adjList.computeIfAbsent(path[0] - 1, __ -> new ArrayList<>()).add(path[1] - 1); |
| 71 | + adjList.computeIfAbsent(path[1] - 1, __ -> new ArrayList<>()).add(path[0] - 1); |
| 72 | + } |
| 73 | + |
| 74 | + return adjList; |
| 75 | + } |
| 76 | +} |
0 commit comments