Topological Sort
- Identify all nodes with no incoming edges
- Add to order
- Remove all outgoing edges
- Repeat
Dijkstra's Algorithm
Finds shortest path from a to b
Setup
- Create
weight
datastructure. Stores for every nodex
the weight froma
tox
. Everything should be infinite excepta
which should be0
. - Create
previous
datastructure. Stores for every nodex
the previous node that leads to the current weight. Should be null for everything - Create
remaining
priority queue. Prioritize on lowest weight. Should start witha
.
Algorithm
- Take the lowest node (
y
) fromremaining
(first time it isa
) - For every neighbor, check the current
weight
withy
's weight + the weight fromy
to neighbor. If y's path is better, updateweight
andprevious
. - Remove
y
. - Repeat.
Why a priority queue?
Because the shortest path has the opportunity for providing a quicker way to other paths. If b
is 3
and c
is 70
, it doesn't make sense to check c
because b
might have a shorter path to c
. Then the check on c
is useless because c
wasn't the shortest.
By checking the shortest first, we guarantee when we get to node x
, there are no other paths to x
that would be shorter, because every other weight is higher.