(W7) Dynamic Programming Flashcards
(10 cards)
What does the Bellman-Ford algorithm do that Dijkstras doesn’t?
can calculate the shortest path even if there are negative edge weights
What are the 2 key ideas of Bellman-Ford?
Cycles with positive weights won’t be part of the shortest path
Any simple path has at most |V|-1 edges
What is the Bellman-Ford Algorithm?
Create a distance and previous array
Mark the starting distance as 0
Iterate over |V|-1 times:
- for each edge (in the whole graph)
- get the updated distance = dist[u] + w(u,v)
- if the distance < distance[v] -> update distance[v] and prev[v] = u
Then - do a final loop check
for each edge in the entire graph
- if distance[u] + w(u,v) < distance[v]
- return an error
What is the complexity (time/space) of Bellman-Ford algorithm
Time: O(VE)
Space: O(V)
What problem does the Floyd-Warshall problem try and solve?
Compute the shortest distance between any 2 pairs of vertices
Is able to work with negative edge weights
What is the Floyd-Warshall Algorithm?
Create an adjacency matrix called dist[][] and preload each edge (u,v) with weight(u,v)
For each vertex k in the graph
- for each pair of vertices (u,v)
if distance[u][k] + distance[k][v] is less than distance[u][v]
- then we have found a shortcut
- distance[u][v] = distance[u][k] + distance[k][v]
What is the complexity of Floyd-Warshall?
Time O(V^3) - this should be obvious from the 3x internal loop
Space (V^2) - creating the distance matrix
What is the key Floyd-Warshall invariant?
For a graph without negative cycles, after the k-th iteration, the distance[i][j] contains the weight of the shortest path that only uses the intermediate nodes from the set {1,…,k}
What properties can you determine about a graph from the Floyd-Warshall distances matrix?
Connectivity - if the distance between u,v is None or Inf - then there is no connecting path
Negative Cycles - if there is any distance[i][i] < 0, then there is a negative cycle
What is transitive closure?
It’s a graph G that only contains an edge between (u,v) if there is a path between (u,v) in the main graph
it can be found using the floyd-warshall algorithm