Dijkstra's Algorithm
Dijkstra's algorithm is run on weighted graphs to find the shortest path.
It only works on Acyclic Graphs with No Negative Edges.
Overview
-
Keep a table of all of the nodes in the graph
-
In the table, keep track of the 'cheapest' cost to get to each node
-
At each step use the
current cheapestnode, see if this node allows us to get to its neighbors for cheaper than any other paths seen so far
| Node | Cost | Processed? | Parent |
|---|---|---|---|
| A | 2 | True | Start |
| B | 3 | False | Start |
| C | NULL | False | NULL |
Dijkstra's Algorithm Steps
-
Pick a
current_node, this will be the cheapest node stored in our table so far. -
We need to update the cost for this node's neighbors.
- We should compare the
neighbor'scurrent total cost (in the table) to the theoretical cost they would have if we used a path fromcurrent_node(total_cost_to_current_node+cost_of_edge_from_current_to_neighbor) - If this new cost is cheaper, update the neighbor's cost and mark it's parent as
current_node
- We should compare the
-
Mark the
current_nodeas processed, do not process it again. -
Repeat until every node in the graph is marked
processed.
Dijkstra's Algorithm vs Breadth First Search
-
Breadth First Searchfinds the shortest path in terms of thenumber of edgesin the path. BFS ignores the weights. -
Dijkstra's Algorithmfinds the shortest path in terms of thetotal combined weightof the edges in the path.
Graph Terminology
- A
Weighted graphhas a number assigned to each edge. This number represents thecostof using that edge. -
An
Unweighted graphhas no numbers on the edges. Each edge has the same cost. -
A
Cycleis a path in a graph that allows you tostart at a node,travel around, andend up where you started.
The Key Idea of Dijkstra's Algorithm
At each step, when you find the cheapest node, the cost currently stored for that node is the lowest that it can possibly ever be.
It is mathematically impossible that you'll find a shorter path to this node later on.
This is why Dijkstra's Algorithm breaks down when you have Negative-Weight edges within a cycle.
In these cases, use something like Bellman-Ford instead.
You might be tempted to think that you can get rid of the negative-weight problem by adding a positive offset to all edges.
The problem is that, although an offset affects all edges equally, it does not affect all paths equally.
Paths of different segment lengths will be changed by differing amounts.
Length : 2
2
A --> B
Length : *3*
3
A --> B
Length : 2
1 1
A --> B --> C
Length : *4*
2 2
A --> B --> C