========================================================
优化的dijkstra算法,已知顶点,求其到其他各个点的最短距离和路径。
增加递归算法记录路径编号。
========================================================
function Dijkstrayouhua(W)
S=input(‘输入终点标号:’);
M=max(max(W));
pb(1:length(W))=0;
pb(1)=1;
index1=1;
index2=ones(1,length(W));
d(1:length(W))=M;
d(1)=0;
temp=1;
while sum(pb)<length(W)
tb=find(pb==0);
d(tb)=min(d(tb),d(temp)+W(temp,tb));
tmpb=find(d(tb)==min(d(tb)));
temp=tb(tmpb(1));
pb(temp)=1;
index1=[index1,temp];
index=index1(find(d(index1)==d(temp)-W(temp,index1)));
if length(index)>=2
index=index(1);
end
index2(temp)=index;
end
d
index1
index2
bj=S;
k=2;
while bj>1
if bj==index2(bj)
bj==1;
disp(‘进入死循环,已为您终止循环!请检查数据正确性。’)
break;
else
MAP(k)=index2(bj);
bj=index2(bj);
k=k+1;
end
end
MAP(1)=S;
if length(MAP)>1
lujing=MAP(end:-1:1) %反序输出
end
========================================================
评:优化后给出了最终的直观路径。
========================================================
例:求下图中顶点1到指定点的最短距离及路径。
解:
(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)带入程序(格式整理后输出如下)
>> Dijkstrayouhua(quanzhijuzhen)
输入终点标号:8
d =
0 2 7 1 3 6 9 11
index1 =
1 4 2 5 6 3 7 8
index2 =
1 1 6 1 2 5 3 5
lujing =
1 2 5 8
说明:增加量路径输出项,1—>8的最短距离11,路径为1—>2—>5—>8