Skip to content

Commit bcbd9ce

Browse files
authored
Merge pull request soapyigu#371 from soapyigu/BFS
Add a solution to Bus Routes
2 parents 4bb1804 + cd6e0de commit bcbd9ce

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

BFS/BusRoutes.swift

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy