Shortest paths and transitive closure

advertisement
Shortest paths and transitive
closure
Data structure
2002/12/4
Is there a path? How short it can be?
 Single source/ All destinations
– Nonnegative edge costs
– General weights
 All-pairs shortest path
 Transitive closure
Single source all destinations
Dijkstra’s algorithm




A spanning tree again
For nonnegative edge costs (Why?)
Start from a vertex v, greedy method
dist[w]: the shortest length to w through S
dist[w]
w
v
length(<u,w>)
dist[u]
u
shortest()
Void shortestpath(int v, int cost[][MAX_VERTICES], int dist [], int n, int found[])
{
int i,u,w;
for (i=0;i<n;i++) {
found[i]=FALSE;
dist [i] = cost[v][i];
}
found[v]=TRUE;
dist [v]=0;
for(i=0;i<n-2;i++){
u=choose(dist,n,found);
found[u]=TRUE;
for(w=0;w<n;w++)
if(dist [u]+cost[u][w] < dist [w])
dist [w] = dist [u]+cost[u][w];
}
}
O(n^2)
An example
Boston
4
1500
San Francisco
1
1200
800
Chicago
3
250
1000
2
Denver
5
300
1000
0
1400
1700
900
7
1000
Los Angeles
New Orleans
6
Miami
New York
Single source all destinations
BellmanFord algorithm




For general weights
Path has at most n-1 edges, otherwise…
distk[u]: from v to u, has at most k edges
dist k [u]  min{ dist k 1[u], min {dist k 1[i]  length[i][u]}}
i
1
6
0
5
-1
4
3
-2
1
2
6
5
-2
3
3
-1
5
0
0
1
6
2
5
3
5
4

5

6

0
0
3
1
3
3
5
5
5
2
4
4

7
0
1
3
5
0
4
5
0
1
3
5
0
4
3
BellmanFord()
Void BellmanFord(int n, int v)
{
int i,k;
for (i =0;i<n;i++)
dist[i] = length[v][i];
for(k=2;k<=n-1;k++)
for(each u s.t. u!=v and u has at least one incoming edge)
for(each <i,u> in the graph)
if(dist([u]>dist[i]+length[i][u])
dist[u]=dist[i]+length[i][u];
}
O(n^3)
All-Pairs shortest paths
 執行n次single source all destinations algo.
 Dynamic programming strategy
– 利用recursive formula 來表示
– 好好地implement recursive formula,用table輔助
 Ak[i][j] ≡ shortest length from i to j through no
intermediate vertex greater than k
 A-1[i][j] = length[i][j]
 Ak[i][j] = min{Ak-1[i][j], Ak-1[i][k]+ Ak-1[k][j], k≥0
AllLengths()
6
Void AllLength(int n)
{
int i,j,k;
0
4
for(i=0;i<n;i++)
for(j=0;j<n;j++)
11
a[i][j] = length[i][j];
3
for(k=0;k<n;k++)
for(i=0;i<n;i++)
2
for(j=0;j<n;j++)
if((a[i][k]+a[k][j])<a[i][j])
a[i][j] = a[i][k]+a[k][j];
}
O(n^3)
1
2
Transitive closure
 Definition: transitive closure matrix, A+
– A+[i][j] = 1, if there’s a path of length > 0 from i to j
– A+[i][j] = 0, otherwise
 Definition: reflexive transitive closure matrix, A*
– A*[i][j] = 1, if there’s a path of length >= 0 from i to j
– A*[i][j] = 0, otherwise
 O(n^3), by AllLengths()
 O(n^2), an undirected graph, by connected check
Download