經典dijkstra算法,已知頂點,求其到其他各個點的最短距離和路徑。
========================================================
function [d index1 index2]=Dijkstra(W)
%d-最短距離,index1-路徑排序(升),index2-指向來源(上一個點,遞歸可得路徑)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;
========================================================
評:只給出了頂點到其他點的最短距離,路徑解不徹底,不能直觀表達路徑。
========================================================
例:求下圖中頂點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)帶入程序(格式整理後輸出如下)
>> [d index1 index2]=Dijkstra(quanzhijuzhen)
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
d——頂點1到點1-8的最短距離分別爲0 2 7 1 3 6 9 11;
index1——到其他點的距離排序,即1最近(0),4次之(1),後依次爲2(2),5(3),6(6),3(7),7(9),8(11);
index2——各點的上游編號,例如到點5的路徑可這樣推算:index2(5)=2,index2(2)=1(已經到頂點,結束),則路徑爲1—>2—>5.