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
| class Solution { public int[] gardenNoAdj(int N, int[][] paths) { int[] result = new int[N]; if (paths.length == 0) { Arrays.fill(result, 1); return result; }
Map<Integer, Set<Integer>> map = new HashMap<>(); for(int[] path: paths){ if (map.containsKey(path[0])) { Set<Integer> curSet = map.get(path[0]); curSet.add(path[1]); map.put(path[0], curSet); }else { Set<Integer> set = new HashSet<>(); set.add(path[1]); map.put(path[0], set); }
if (map.containsKey(path[1])) { Set<Integer> curSet = map.get(path[1]); curSet.add(path[0]); map.put(path[1], curSet); }else { Set<Integer> set = new HashSet<>(); set.add(path[0]); map.put(path[1], set); } }
result[0] = 1; for (int i = 2; i <= N; i++) { Set<Integer> aSet = new HashSet<>(); Set<Integer> s = map.get(i); if (s != null) { for (Integer o : s) { if (result[o - 1] != 0) { aSet.add(result[o - 1]); } } }
for (int j = 1; j <= 4; j++) { if (!aSet.contains(j)) { result[i-1] = j; break; } } } return result; } }
|