赞
踩
1)求每对顶点的最短路径;
2)有向图、无向图和混合图;
直接在图的带权邻接矩阵中用插入顶点的方法依次递推地构造出n个矩阵D(1), D(2), …, D(n), D(n)是图的距离矩阵, 同时引入一个后继点矩阵记录两点间的最短路径.
d(i,j) : i到j的距离;
path(i,j): i到j的路径上i的后继点;
输入带权邻接矩阵a(i,j).
1)赋初值
对所有i,j, d(i,j)⬅a(i,j) , path(i,j)⬅j,k=l.
2)更新d(i,j) , path(i,j)
对所有i,j, 若d(i,k)+d(k,j)<d(i,j),则
d(i,j)⬅d(i,k)+d(k,j) , path(i,j)⬅path(i,k) , k ⬅k+1
3)重复2)直到k=n+1
Floyd算法程序的使用说明:
1. [D, path]=floyd(a), 返回矩阵D, path 。其中a是所求图的带权邻接矩阵,D(i,j)表示i到j的最短距离; path(i,j)表示i与j之间的最短路径上顶点i的后继点.
2. [D, path, min1, path1]= floyd(a,i,j) 返回矩阵D, path; 并返回i与j之间的最短距离min1和最短路径path1.
- function [D,path,min1,path1]=floyd(a,start,terminal)
- D=a;n=size(D,1);path=zeros(n,n);
- for i=1:n
- for j=1:n
- if D(i,j)~=inf
- path(i,j)=j;
- end, end, end
- for k=1:n
- for i=1:n
- for j=1:n
- if D(i,k)+D(k,j)<D(i,j)
- D(i,j)=D(i,k)+D(k,j);
- path(i,j)=path(i,k);
- end, end, end,end
-
- if nargin==3
- min1=D(start,terminal);
- m(1)=start;
- i=1;
- path1=[ ];
- while path(m(i),terminal)~=terminal
- k=i+1;
- m(k)=path(m(i),terminal);
- i=i+1;
- end
- m(i+1)=terminal;
- path1=m;
- end
- a =[ 0 2 8 1 Inf Inf Inf Inf Inf Inf Inf;
- 2 0 6 Inf 1 Inf Inf Inf Inf Inf Inf;
- 8 6 0 7 5 1 2 Inf Inf Inf Inf;
- 1 Inf 7 0 Inf Inf 9 Inf Inf Inf Inf;
- Inf 1 5 Inf 0 3 Inf 2 9 Inf Inf;
- Inf Inf 1 Inf 3 0 4 Inf 6 Inf Inf;
- Inf Inf 2 9 Inf 4 0 Inf 3 1 Inf;
- Inf Inf Inf Inf 2 Inf Inf 0 7 Inf 9;
- Inf Inf Inf Inf 9 6 3 7 0 1 2;
- Inf Inf Inf Inf Inf Inf 1 Inf 1 0 4;
- Inf Inf Inf Inf Inf Inf Inf 9 2 4 0];
- start = 1;
- terminal = 11;
- [D,path,min1,path1]=floyd(a,start,terminal)
- min1 =
-
- 13
-
-
- path1 =
-
- 1 2 5 6 3 7 10 9 11
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。