Graph Theory37 sections · 1633 units
Open in Course

LeetCode 787 Cheapest Flights Within K Stops - Walkthrough

(Trace execution)

Input: n=3n=3, edges =[(0,1,100),(1,2,100),(0,2,500)]= [(0,1,100), (1,2,100), (0,2,500)], src=0src=0, dst=2dst=2, k=1k=1. Iteration 11: prev = [0, Infinity, Infinity]. Relax edges: dist[1] = 100, dist[2] = 500. Iteration 22: prev = [0, 100, 500]. Relax edges: dist[2] can improve via 0120 \to 1 \to 2 using prev[1] + 100 = 200.

Final dist[2] = 200. This path uses 11 stop (city 11), which satisfies k=1k=1. The direct flight costs 500500, but the one-stop route costs 200200.