圖論02—任意兩點間最短距離及路徑(經典)

========================================================
求任意兩點間最短距離及其路徑。(萬能最短路)
輸入:權值矩陣,起點,終點
輸出:最短距離矩陣,指定起訖點路徑(經過的頂點編號)
爲任意一點到其他點最短路奠定基礎
========================================================
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.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章