Graph Theory37 sections · 1633 units
Open in Course

LeetCode 787 Cheapest Flights Within K Stops - Visited Set

Revisiting nodes in expanded state

In standard Dijkstra, once you visit a node, you never visit it again. Here, you might visit the same city multiple times with different k values. Example: You reach city 55 with k = 1 at cost 100100. Later, you reach city 55 with k = 3 at cost 120120. The second visit is worse by cost, but it has more stops remaining.

It might find a cheaper path to the destination. Solution: Track visited as (city, stops_remaining) pairs. Or skip the visited set entirely and rely on the heap to naturally handle duplicates. The heap ensures you process the cheapest state first, so suboptimal revisits get ignored when you pop them.