Definition
Dijkstra's Algorithm is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge weights, producing a shortest-path tree. It finds the minimum distance from a starting node to all other nodes in the graph.
Constraints
- Requires non-negative edge weights (fails with negative weights)
- Optimal for graphs with reasonable edge density
- Not suitable for graphs with negative cycles (use Bellman-Ford instead)
- Performance degrades for very large sparse graphs
Step-by-step explanation
Arguments:
- Graph representation -
graph
- Starting node -
source
- Distance array -
dist[]
- Priority queue/min-heap -
priorityQueue
- Visited nodes set -
visited
Explanation:
- Initialize all distances as INFINITY except the source node (distance 0)
- While there are unvisited nodes:
- Select the unvisited node with the smallest known distance
- For each neighbor of the current node:
- Calculate tentative distance through current node
- Update neighbor's distance if tentative distance is smaller
- Mark current node as visited
- After processing all nodes,
dist[]
contains shortest distances from source
Returns:
Returns a distance array where each index represents the shortest distance from the source node
Can optionally return a predecessor array to reconstruct paths
Returns null
if negative weights are detected