Dijkstra's Algorithm
Shortest distance from a source to every vertex, with non-negative edge weights.
Open on GeeksforGeeks ↗Intuition
Repeatedly finalise the nearest vertex that is not yet settled. This works precisely because weights are non-negative: any other route to that vertex would have to pass through something even further away, which can only add cost. So the closest unsettled vertex can never improve later — settle it and relax its edges.
Approach
Greedy settle order
Keep tentative dist[], all ∞ except the source. Pick the smallest unsettled distance, mark it settled, and relax its outgoing edges: dist[v] = min(dist[v], dist[u] + w).
Use a heap
Scanning for the minimum is O(V) per step, giving O(V²). A binary heap makes it O(log V), for O((V + E) log V) overall — push improved distances and skip stale heap entries.
Why negative weights break it
A negative edge could make a far-away route cheaper after a vertex was settled, violating the settle-once guarantee. Use Bellman–Ford in that case.
Solution & live demo
Edge cases
Distance stays ∞.
Pop and skip any entry whose distance exceeds the recorded dist[u].
Fine — only strictly negative weights break the argument.