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
weightdatastructure. Stores for every nodexthe weight fromatox. Everything should be infinite exceptawhich should be0. - Create
previousdatastructure. Stores for every nodexthe previous node that leads to the current weight. Should be null for everything - Create
remainingpriority 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
weightwithy's weight + the weight fromyto neighbor. If y's path is better, updateweightandprevious. - 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.