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
| class Solution { public int numBusesToDestination(int[][] routes, int source, int target) { if (source == target) { return 0; }
int buses = 1; boolean[] visited = new boolean[routes.length]; Map<Integer, Set<Integer>> stationToLineSetMap = new HashMap<>();
Queue<Integer> queue = new LinkedList<>();
for (int lineIndex = 0; lineIndex < routes.length; lineIndex++) { for (int station : routes[lineIndex]) { if (station == source) { queue.offer(lineIndex); visited[lineIndex] = true; }
stationToLineSetMap.computeIfAbsent(station, key -> new HashSet<>()).add(lineIndex); } }
while (!queue.isEmpty()) { for (int i = queue.size(); i > 0; i--) { int lineIndex = queue.poll();
for (int station : routes[lineIndex]) { if (station == target) { return buses; }
for (int line : stationToLineSetMap.get(station)) { if (visited[line]) { continue; } queue.offer(line); visited[line] = true; } } }
buses++; }
return -1; } }
|
关键解题思路:对路线进行 BFS 遍历,遍历过程中检查站点是否满足条件。
References
815. Bus Routes