========================================================
求随意两点间最短距离及其路径。(万能最短路)
输入:权值矩阵,起点。终点
输出:最短距离矩阵。指定起讫点路径(经过的顶点编号)
为随意一点到其它点最短路奠定基础
========================================================
function [P d]=liangdianzuiduanlu(W,qidian,zhongdian)
W;
n=length(W);
D=W;
m=1;
while m<=n
for i=1:n
for j=1:n
if D(i,j)>D(i,m)+D(m,j)
D(i,j)=D(i,m)+D(m,j);
end
end
end
m=m+1;
end
d=D(qidian,zhongdian);
P1=zeros(1,n);
k=1;
P1(k)=zhongdian;
V=ones(1,n)*inf;
kk=zhongdian;
while kk~=qidian;
for i=1:n
V(1,i)=D(qidian,kk)-W(i,kk);
if V(1,i)==D(qidian,i)
P1(k+1)=i;
kk=i;
k=k+1;
end
end
end
k=1;
wrow=find(P1~=0);
for j=length(wrow):(-1):1
P(k)=P1(wrow(j));
k=k+1;
求随意两点间最短距离及其路径。(万能最短路)
输入:权值矩阵,起点。终点
输出:最短距离矩阵。指定起讫点路径(经过的顶点编号)
为随意一点到其它点最短路奠定基础
========================================================
function [P d]=liangdianzuiduanlu(W,qidian,zhongdian)
W;
n=length(W);
D=W;
m=1;
while m<=n
for i=1:n
for j=1:n
if D(i,j)>D(i,m)+D(m,j)
D(i,j)=D(i,m)+D(m,j);
end
end
end
m=m+1;
end
d=D(qidian,zhongdian);
P1=zeros(1,n);
k=1;
P1(k)=zhongdian;
V=ones(1,n)*inf;
kk=zhongdian;
while kk~=qidian;
for i=1:n
V(1,i)=D(qidian,kk)-W(i,kk);
if V(1,i)==D(qidian,i)
P1(k+1)=i;
kk=i;
k=k+1;
end
end
end
k=1;
wrow=find(P1~=0);
for j=length(wrow):(-1):1
P(k)=P1(wrow(j));
k=k+1;
end
========================================================
评:缺点是与人的衔接功能不好,下一篇《改进的随意两点间最短距离及路
径》将会解决这个缺点。
========================================================
例:求下图中点1到8的最短距离和路径
解:(1)写权值矩阵
quanzhijuzhen=[ 0 2 8 1 Inf Inf Inf Inf
2 0 6 Inf 1 Inf Inf Inf
8 6 0 7 5 1 2 Inf
1 Inf 7 0 Inf Inf 9 Inf
Inf 1 5 Inf 0 3 Inf 8
Inf Inf 1 Inf 3 0 4 6
Inf Inf 2 9 Inf 4 0 3
Inf Inf Inf Inf 8 6 3 0]
(2)带入程序
[P d]=liangdianzuiduanlu(quanzhijuzhen,1,8)
P =
1 2 5 8
d =
11
说明:路径为1->2->5->8,最短距离为11.