图——所有顶点间的最短路径

floyd算法,求任意两点间最短距离

 

//算法思想:floyd是动态规划算法,cost[i][j],表示i,j间的最短路径,
//对cost不断更新,每次更新是让 i->j 经过k(0,n),
//比如:在k次更新时,即i->j 经过k,如果 i->k->j 比 i>k-1>j(上一次k-1时更新)要小,则设置cost[i][j],表示经过k,有最短路径
//则样不断重复 k=n 次循环,则可算出,cost[i][j] 最短路径,每个经过的点,都是在(0,n)中,选出最小的。
//时间复杂度O(n^3)

Floyd
  1 void Graph::Floyd()
2 {
3 int MAX_INF=10000;
4 int cost[max_vertexs][max_vertexs]; //两点间最短距离代价矩阵
5 int path[max_vertexs][max_vertexs]; //最短距离,经过的中间节点
6
7 int n=vertex;
8 for (int i=0;i<n;i++)
9 for(int j=0;j<n;j++)
10 {
11 cost[i][j]=(graph[i][j]>0||i==j)?graph[i][j]:MAX_INF;
12 path[i][j]=-1;
13 }
14
15 for(int k=0;k<n;k++)
16 {
17 //更细cost,中间经过k节点
18 for (int i=0;i<n;i++)
19 for (int j=0;j<n;j++)
20 {
21 //经过k,cost[i][j]更优化
22 if(cost[i][k]+cost[k][j]<cost[i][j])
23 {
24 cost[i][j]=cost[i][k]+cost[k][j];
25 path[i][j]=k;
26 }
27 }
28 }
29
30 for (i=0;i<n;i++)
31 {
32 for(int j=0;j<n;j++)
33 cout<<cost[i][j]<<' ';
34 cout<<endl;
35 }
36
37 cout<<"**********************"<<endl;
38
39 for (i=0;i<n;i++)
40 {
41 for(int j=0;j<n;j++)
42 cout<<path[i][j]<<' ';
43 cout<<endl;
44 }
45
46 stack<int> stack; //依次进栈2次j,i,表示从路径要经过i->j
47 Queue<int> queue; //重i->j 之间要经过的节点
48
49 for (i=0;i<n;i++)
50 for (int j=0;j<n;j++)
51 {
52 //没有路径
53 if (i==j)
54 {
55 continue;
56 }
57 else if (cost[i][j]>=MAX_INF)
58 {
59 printf("v%d-->v%d : has no path!\n",i,j);
60 continue;
61 }
62 else
63 {
64 //寻找i和j间的最短路径
65 printf("v%d-->v%d : path is:(",i,j);
66
67 //初始化
68 stack.push(j);
69 stack.push(i);
70 queue.push(i);
71
72 int from,to;
73 while (1)
74 {
75 if (stack.isEmpty())
76 {
77 break;
78 }
79
80 from=stack.Top();
81 stack.pop();
82 to=stack.Top();
83 stack.pop();
84
85 int mid=path[from][to];
86 if (mid>0)
87 {
88 //from to 有中间结点
89 stack.push(to);
90 stack.push(mid);
91 stack.push(mid);
92 stack.push(from);
93 }
94 else
95 {
96 queue.push(to);
97 }
98
99 }
100
101 //输出从 i->j 的路径
102 while(!queue.isEmpty())
103 {
104 printf("v%d ",queue.Front());
105 queue.pop();
106 }
107
108 printf(") length : %d\n",cost[i][j]);
109
110 }
111
112 }
113
114 }
posted on 2011-09-17 19:48  youngkang  阅读(313)  评论(0)    收藏  举报