|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.HashSet; |
| 5 | +import java.util.LinkedList; |
| 6 | +import java.util.Map; |
| 7 | +import java.util.Queue; |
| 8 | +import java.util.Set; |
| 9 | + |
| 10 | +public class _1466 { |
| 11 | + public static class Solution1 { |
| 12 | + public int minReorder(int n, int[][] connections) { |
| 13 | + //key is entering city, value is departure city |
| 14 | + Map<Integer, Set<Integer>> map = new HashMap<>(); |
| 15 | + Queue<Integer> queue = new LinkedList<>(); |
| 16 | + int minReorder = 0; |
| 17 | + Set<Integer> visited = new HashSet<>(); |
| 18 | + for (int i = 0; i < n; i++) { |
| 19 | + visited.add(i); |
| 20 | + } |
| 21 | + |
| 22 | + //key is departure city, value is entering city |
| 23 | + Map<Integer, Set<Integer>> reverseMap = new HashMap<>(); |
| 24 | + for (int[] con : connections) { |
| 25 | + if (!map.containsKey(con[1])) { |
| 26 | + map.put(con[1], new HashSet<>()); |
| 27 | + } |
| 28 | + map.get(con[1]).add(con[0]); |
| 29 | + |
| 30 | + if (!reverseMap.containsKey(con[0])) { |
| 31 | + reverseMap.put(con[0], new HashSet<>()); |
| 32 | + } |
| 33 | + reverseMap.get(con[0]).add(con[1]); |
| 34 | + |
| 35 | + //for all those directly connected to city 0, must be reordered if not yet |
| 36 | + //and they are the start nodes of BFS |
| 37 | + if (con[0] == 0) { |
| 38 | + minReorder++; |
| 39 | + queue.offer(con[1]); |
| 40 | + visited.remove(con[1]); |
| 41 | + visited.remove(0); |
| 42 | + } |
| 43 | + if (con[1] == 0) { |
| 44 | + queue.offer(con[0]); |
| 45 | + visited.remove(0); |
| 46 | + } |
| 47 | + } |
| 48 | + while (!queue.isEmpty() || !visited.isEmpty()) { |
| 49 | + int curr = queue.poll(); |
| 50 | + visited.remove(curr); |
| 51 | + if (map.containsKey(curr)) { |
| 52 | + Set<Integer> departureCityList = map.get(curr); |
| 53 | + for (int city : departureCityList) { |
| 54 | + if (visited.contains(city)) { |
| 55 | + queue.offer(city); |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + if (reverseMap.containsKey(curr)) { |
| 60 | + Set<Integer> enteringCityList = reverseMap.get(curr); |
| 61 | + for (int city : enteringCityList) { |
| 62 | + if (visited.contains(city)) { |
| 63 | + queue.offer(city); |
| 64 | + minReorder++; |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + return minReorder; |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments