forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
bus-routes.py
67 lines (60 loc) · 1.81 KB
/
bus-routes.py
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
63
64
65
66
67
# Time: O(|V| + |E|)
# Space: O(|V| + |E|)
# 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.
import collections
class Solution(object):
def numBusesToDestination(self, routes, S, T):
"""
:type routes: List[List[int]]
:type S: int
:type T: int
:rtype: int
"""
if S == T:
return 0
to_route = collections.defaultdict(set)
for i, route in enumerate(routes):
for stop in route:
to_route[stop].add(i)
result = 1
q = [S]
lookup = set([S])
while q:
next_q = []
for stop in q:
for i in to_route[stop]:
for next_stop in routes[i]:
if next_stop in lookup:
continue
if next_stop == T:
return result
next_q.append(next_stop)
to_route[next_stop].remove(i)
lookup.add(next_stop)
q = next_q
result += 1
return -1