File tree 1 file changed +58
-0
lines changed
1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Question Link: https://leetcode.com/problems/bus-routes/
3
+ * Primary idea: BFS. Build a map for stop and related buses' indexes map. Use a queue to track until the current stop is equal to the target.
4
+ *
5
+ * Time Complexity: O(nm), Space Complexity: O(nm)
6
+ *
7
+ */
8
+
9
+ class BusRoutes {
10
+ func numBusesToDestination( _ routes: [ [ Int ] ] , _ source: Int , _ target: Int ) -> Int {
11
+
12
+ if source == target {
13
+ return 0
14
+ }
15
+
16
+ let stopBusesMap = buildMap ( routes)
17
+
18
+ // bfs
19
+ var queue = [ source] , res = 0 , isVisited = Set < Int > ( )
20
+
21
+ while !queue. isEmpty {
22
+ let size = queue. count
23
+
24
+ for _ in 0 ..< size {
25
+ let stop = queue. removeFirst ( )
26
+
27
+ if stop == target {
28
+ return res
29
+ }
30
+
31
+ for busIdx in stopBusesMap [ stop] ?? [ ] {
32
+ guard !isVisited. contains ( busIdx) else {
33
+ continue
34
+ }
35
+
36
+ isVisited. insert ( busIdx)
37
+ queue. append ( contentsOf: routes [ busIdx] )
38
+ }
39
+ }
40
+
41
+ res += 1
42
+ }
43
+
44
+ return - 1
45
+ }
46
+
47
+ private func buildMap( _ routes: [ [ Int ] ] ) -> [ Int : Set < Int > ] {
48
+ var stopBusesMap = [ Int : Set < Int > ] ( )
49
+
50
+ for (i, bus) in routes. enumerated ( ) {
51
+ bus. forEach {
52
+ stopBusesMap [ $0, default: Set < Int > ( ) ] . insert ( i)
53
+ }
54
+ }
55
+
56
+ return stopBusesMap
57
+ }
58
+ }
You can’t perform that action at this time.
0 commit comments