Skip to content

Commit 2985760

Browse files
committed
Add a solution to the Cheapest Flights Within K Stops
1 parent a54370d commit 2985760

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Graph/CheapestFlightsKStops.swift

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/cheapest-flights-within-k-stops/
3+
* Primary idea: Topological sort + BFS.
4+
* Build a graph with each srouce and destination as an edge. Put the source as the head node for the queue, visit every possible destinaiton and update the result with the possible smallest value.
5+
*
6+
* Time Complexity: O(n * (n - 1) + K), Space Complexity: O(n * (n - 1)),
7+
* n represents number of the cities
8+
*/
9+
10+
class CheapestFlightsKStops {
11+
func findCheapestPrice(_ n: Int, _ flights: [[Int]], _ src: Int, _ dst: Int, _ k: Int) -> Int {
12+
var srcDestinations = buildGraph(flights)
13+
var queue = [(src, 0)], dstPrice = [Int: Int](), stopCount = 0
14+
15+
while !queue.isEmpty && stopCount < k + 1 {
16+
17+
let currentQueueLen = queue.count
18+
19+
for _ in 0..<currentQueueLen {
20+
let (from, fromPrice) = queue.removeFirst()
21+
22+
guard let destinations = srcDestinations[from] else {
23+
continue
24+
}
25+
26+
for (to, price) in destinations {
27+
if let prevPrice = dstPrice[to], prevPrice <= fromPrice + price {
28+
continue
29+
} else {
30+
dstPrice[to] = fromPrice + price
31+
queue.append((to, fromPrice + price))
32+
}
33+
}
34+
35+
}
36+
stopCount += 1
37+
}
38+
39+
return dstPrice[dst] ?? -1
40+
}
41+
42+
// src -> (dst, price)
43+
private func buildGraph(_ flights: [[Int]]) -> [Int: [(Int, Int)]] {
44+
var srcDestinations = [Int: [(Int, Int)]]()
45+
46+
for flight in flights {
47+
srcDestinations[flight[0], default:[(Int, Int)]()].append((flight[1], flight[2]))
48+
}
49+
50+
return srcDestinations
51+
}
52+
}

0 commit comments

Comments
 (0)