You are on page 1of 15

Single Source Shortest Path

• Greedy Method
– Dijkstra’s Algorithm

• Dynamic Programming
– Bellman Ford Algorithm
Single Source Shortest Path
• Greedy Method
– Dijkstra’s Algorithm

• Dynamic Programming
– Bellman Ford Algorithm
Single Source Shortest Path
• Greedy Method
– Dijkstra’s Algorithm
• Negative Edges are not permitted

• Dynamic Programming
– Bellman Ford Algorithm
• Negative Edges are permitted
• Negative Cycles are not permitted
Graph with negative edges

1 2 3
7 -5
Graph with negative cycle

1 2 3
-7 2
-1
2 5
6 3
-2
1
5
1 3 7

-2
5
3
4 6
-1

1 2 3 4 5 6 7
0
1
2
3
4
5
6
Bellman Ford – Algorithm
Algo BellmanFord(v, cost, dist, n)
{ for i = 1 to n do
{dist[i] = infinity;}
dist[v] = 0;
for k = 1 to n-1 do
for each vertex u ≠ v do
distnew[u] = dist[u]
for each edge(i,u) do
distnew[u] = min(distnew[u], dist[i] + cost(i,u));
for each vertex u ≠ v do
dist[u] = distnew[u]
}
-1
2 5
6 3
-2
1
5
1 3 7

-2
5
3
4 6
-1

1 2 3 4 5 6 7
0 0 - - - - - -
1
2
3
4
5
6
Bellman Ford – Algorithm
Algo BellmanFord(v, cost, dist, n)
{ for i = 1 to n do
{dist[i] = infinity;}
dist[v] = 0;
for k = 1 to n-1 do
for each vertex u ≠ v do
distnew[u] = dist[u]
for each edge(i,u) do
distnew[u] = min(distnew[u], dist[i] + cost(i,u));
for each vertex u ≠ v do
dist[u] = distnew[u]
}
-1
2 5
6 3
-2
1
5
1 3 7

-2
5
3
4 6
-1

1 2 3 4 5 6 7
0 0 - - - - - -
1 0 6 5 5 - - -
2
3
4
5
6
-1
2 5
6 3
-2
1
5
1 3 7

-2
5
3
4 6
-1

1 2 3 4 5 6 7
0 0 - - - - - -
1 0 6 5 5 - - -
2 0 3 3 5 5 4 -
3
4
5
6
-1
2 5
6 3
-2
1
5
1 3 7

-2
5
3
4 6
-1

1 2 3 4 5 6 7
0 0 - - - - - -
1 0 6 5 5 - - -
2 0 3 3 5 5 4 -
3 0 1 3 5 2 4 7
4
5
6
-1
2 5
6 3
-2
1
5
1 3 7

-2
5
3
4 6
-1

1 2 3 4 5 6 7
0 0 - - - - - -
1 0 6 5 5 - - -
2 0 3 3 5 5 4 -
3 0 1 3 5 2 4 7
4 0 1 3 5 0 4 5
5
6
-1
2 5
6 3
-2
1
5
1 3 7

-2
5
3
4 6
-1

1 2 3 4 5 6 7
0 0 - - - - - -
1 0 6 5 5 - - -
2 0 3 3 5 5 4 -
3 0 1 3 5 2 4 7
4 0 1 3 5 0 4 5
5 0 1 3 5 0 4 3
6
-1
2 5
6 3
-2
1
5
1 3 7

-2
5
3
4 6
-1

1 2 3 4 5 6 7
0 0 - - - - - -
1 0 6 5 5 - - -
2 0 3 3 5 5 4 -
3 0 1 3 5 2 4 7
4 0 1 3 5 0 4 5
5 0 1 3 5 0 4 3
6 0 1 3 5 0 4 3

You might also like