forked from ex01tus/leetcode-grind
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBusRoutes.java
More file actions
62 lines (51 loc) · 1.84 KB
/
BusRoutes.java
File metadata and controls
62 lines (51 loc) · 1.84 KB
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
61
62
package graph;
import java.util.*;
/**
* Description: https://leetcode.com/problems/bus-routes
* Difficulty: Hard
* Time complexity: O(n)
* Space complexity: O(n)
*/
public class BusRoutes {
public int numBusesToDestination(int[][] routes, int source, int target) {
if (source == target) return 0;
Map<Integer, List<Integer>> stopToBusesMap = buildStopToBusesMap(routes);
return countMinBusNumber(stopToBusesMap, routes, source, target);
}
private int countMinBusNumber(
Map<Integer, List<Integer>> stopToBusesMap,
int[][] routes,
int source,
int target) {
int[] usedBuses = new int[routes.length];
Queue<Integer> planned = new LinkedList<>();
planned.offer(source);
int buses = 0;
while (!planned.isEmpty()) {
int levelSize = planned.size();
buses++;
for (int i = 0; i < levelSize; i++) {
int currentStop = planned.poll();
for (int bus : stopToBusesMap.getOrDefault(currentStop, List.of())) {
if (usedBuses[bus] != 0) continue;
usedBuses[bus] = 1;
for (int nextStop : routes[bus]) {
if (nextStop == target) return buses;
planned.offer(nextStop);
}
}
}
}
return -1;
}
private Map<Integer, List<Integer>> buildStopToBusesMap(int[][] routes) {
Map<Integer, List<Integer>> stopToBusesMap = new HashMap<>();
for (int bus = 0; bus < routes.length; bus++) {
int[] stops = routes[bus];
for (int stop : stops) {
stopToBusesMap.computeIfAbsent(stop, __ -> new ArrayList<>()).add(bus);
}
}
return stopToBusesMap;
}
}