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
| class Solution { public int numBusesToDestination(int[][] routes, int source, int target) { if (source == target) return 0; int n = routes.length; Map<Integer, Set<Integer>> map = new HashMap<>(); Deque<Integer> queue = new ArrayDeque<>(); Map<Integer, Integer> stepMap = new HashMap<>(); for (int i = 0; i < n; ++i) { for (int s : routes[i]) { if (s == source) { queue.offer(i); stepMap.put(i, 1); } Set<Integer> set = map.getOrDefault(s, new HashSet<>()); set.add(i); map.put(s, set); } } while (!queue.isEmpty()) { int cur = queue.poll(); int step = stepMap.get(cur); for (int i : routes[cur]) { if (i == target) return step; Set<Integer> set = map.get(i); if (set == null) continue; for (Integer line : set) { if (!stepMap.containsKey(line)) { stepMap.put(line, step + 1); queue.offer(line); } } } } return -1; } }
|