Professional Documents
Culture Documents
1
Shortest path problems
18 4
2 12 6
10
10
5 3 5
3
1 8
1 4
5
7 7
2
Dynamic programming principle
vi = min(gij + vj )
j
18 4
2 12 6
10
10
5 3 5
3
1 8
1 4
5
7 7
3
Dynamic programming principle
6
18 4
19 2 12 6
10
vi = min(gij + vj ) 10
j 5 9 3 5 0
3
1 8
12 1 4
5
7 7 8
I starting at vertex i 6
13
I gij is cost of next step
4
Dynamic programming principle
6
18 4
19 2 12 6
10
vi = min(gij + vj ) 10
j 5 9 3 5 0
3
1 8
12 1 4
5
7 7 8
6
13
I once we know v, we also know the optimal path from all initial vertices
5
Bellman-Ford algorithm
(
0 if i = destination
I let vi0 =
∞ otherwise
I for k = 0, . . . , n − 1
k+1
I vi = min{vik , min(gij + vjk )}
j
I if v n 6= v n−1 then graph has negative cycle, and cost may be made −∞
6
Bellman-Ford algorithm
6
18 4
19 2 12 6
10
10
5 9 3 5 0
vik+1 = min{vik , min(gij + vjk )}
j 3
1 8
12 1 4
5
7 7 8
6
13
∞ ∞ 13 12
∞ ∞ 20 19
∞ 10 9 9
v0 = v1 = v2 = v3 =
∞ 6 6 6
0 0 0 0
∞ ∞ 14 13
∞ 8 8 8
7
Dynamic programming
I works backward in time (for deterministic problems, can also work forwards)
8
Shortest path problems
I Dijkstra’s algorithm is similar but faster (O(m + n log n)), and requires non-
negative weights
I both BF and Dijkstra give shortest path from every vertex to destination