Description
We have a list of bus routes. Each routes[i]
is a bus route that the i-th bus repeats forever. For example if routes[0] = [1, 5, 7]
, this means that the first bus (0-th indexed) travels in the sequence 1->5->7->1->5->7->1->... forever.
We start at bus stop S
(initially not on a bus), and we want to go to bus stop T
. Travelling by buses only, what is the least number of buses we must take to reach our destination? Return -1 if it is not possible.
Example:
Input:
routes = [[1, 2, 7], [3, 6, 7]]
S = 1
T = 6
Output: 2
Explanation:
The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.
Note:
-
1 <= routes.length <= 500
. -
1 <= routes[i].length <= 500
. -
0 <= routes[i][j] < 10 ^ 6
.
Solution
BFS, O(n ^ 2), S(n*L + edges)
很有趣的题,很容易被障眼法迷惑住,如果一旦将每个站点作为Graph Node,感觉这题就没救儿了。。
正确的做法是,将Bus作为Graph Node!然后根据Bus之间是否有公共站点,来build graph。最后直接BFS就行了。
class Solution {
public int numBusesToDestination(int[][] routes, int s, int t) {
if (s == t) {
return 0;
}
int n = routes.length;
// each bus is a node with id (routes index)
Map<Integer, List<Integer>> graph = new HashMap<>();
// stops(i) is just a copy of routes[i] for fast accessing
Map<Integer, Set<Integer>> stops = new HashMap<>();
for (int i = 0; i < n; ++i) {
graph.put(i, new ArrayList<>());
Set<Integer> path = new HashSet<>();
for (int j : routes[i]) {
path.add(j);
}
stops.put(i, path);
}
// build graph, just add edge to buses that have intersection
for (int i = 0; i < n - 1; ++i) {
for (int j = i + 1; j < n; ++j) {
if (hasIntersect(stops.get(i), stops.get(j))) {
graph.get(i).add(j);
graph.get(j).add(i);
}
}
}
// normal BFS
Queue<int[]> queue = new LinkedList<>();
Set<Integer> used = new HashSet<>();
for (int i = 0; i < n; ++i) {
if (stops.get(i).contains(s)) {
queue.offer(new int[] {i, 1});
used.add(i);
}
}
while (!queue.isEmpty()) {
int[] arr = queue.poll();
int i = arr[0];
int depth = arr[1];
if (stops.get(i).contains(t)) {
return depth;
}
for (int next : graph.get(i)) {
if (used.add(next)) {
queue.offer(new int[] {next, depth + 1});
}
}
}
return -1;
}
private boolean hasIntersect(Set<Integer> set1, Set<Integer> set2) {
Iterator<Integer> iter1 = set1.iterator();
while (iter1.hasNext()) {
if (set2.contains(iter1.next())) {
return true;
}
}
return false;
}
}