6 DP Floyd Warshall
Bellman ford finds the shortest path from all nodes to some goal node
Idk why this was mentioned but: Dealing with sinks: A sink is a node
where all nodes are directed to it and nothing flows out of
Why Floyd-Warshall¶
This algorithm floyd-warshall is a way to find all-pair shortest paths, where all-pair shortest paths finds the shortest paths between each pair of node. It is still
To do this with bellman ford, we would have to compute the algorithm for each vertex/node
In Bellman Ford:¶
- Suppose a shortest path from
is , then the shortest path from and are already known, because by definition bellman ford will have already taken the shortest path through theses nodes.
Method¶
- Order the vertices
and consider them in order. - For each pair
, the initial shortest path is the weight of the edge between them, if it exists. Otherwise we set it to . (Basically just the adjacency matrix) - On the first iteration
, we consider including vertex on the shortest path.- Is there an edge
and a edge such that their sum is less than the weight between ?
- Is there an edge
- On the second iteration, we look if there are any shorter paths containing
and .
Basically,
Perhaps at each iteration, when we look at each pair
, we also allow the algorithm to look at the adjacency lists
We can define the recurrence relation as:
Example¶
For detecting cycles: If the weight from a given node to itself decreases, then we know we have found a negative cycle. AKA Just check the diagonal of the table
Pseudocode¶
Proving correctness¶