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
| class Solution {
Map<Integer, List<Integer>> g = new HashMap<>();
private void add(int a, int b) { g.computeIfAbsent(a, key -> new ArrayList<>()).add(b); }
public int[] gardenNoAdj(int n, int[][] paths) { for (int[] path : paths) { int x = path[0] - 1, y = path[1] - 1; add(x, y); add(y, x); } int[] ans = new int[n]; for (int x = 0; x < n; ++x) { boolean[] used = new boolean[5]; List<Integer> list = g.getOrDefault(x, new ArrayList<>()); for (int y : list) used[ans[y]] = true; for (int c = 1; c < 5; ++c) { if (!used[c]) { ans[x] = c; break; } } } return ans; } }
|