<span style="font-family: Arial, Helvetica, sans-serif;">%% Dijkstra </span>
function minWeightMatrix=shortestPath(G,nodeNum)
minWeightMatrix=zeros(nodeNum,nodeNum);
for i=1:nodeNum %獲取每個頂點到其它節點最短路徑權值,Dijkstra 源點遍歷
D=G(i,:); %初始化節點到各個鄰居節點的權值
D(D==0)=inf;
tag=zeros(1,nodeNum); %0 爲對應位置節點未求出最大路徑
tag(i)=1;
while sum(tag,2)~=nodeNum
noTag=find(tag==0); %還未獲得最短距離的節點
minValue=min(D(noTag));
if minValue~=inf
tempIndex=find(D==minValue); %找出候選節點,更新值
tag(tempIndex)=1;
% 將候選節點去掉
for candidateNode=1:length(tempIndex)
noTag(noTag==tempIndex(candidateNode))=[];
end
% 修改源點到各個未標記的頂點間的距離
for j=1:length(noTag) %對所有未獲得最短距離的節點進行更新
minTemp=D(noTag(j));
for k=1:length(tempIndex)
if minTemp>(minValue+G(tempIndex(k),noTag(j)))&&G(tempIndex(k),noTag(j))~=0
minTemp=minValue+G(tempIndex(k),noTag(j));
end
end
D(noTag(j))=minTemp;
end
else
break;
end
end
minWeightMatrix(i,:)=D;
end
minWeightMatrix(isinf(minWeightMatrix))=0;
minWeightMatrix=minWeightMatrix-diag(diag(minWeightMatrix));
測試數據:
clear;clc;
%% 測試數據
%有向圖範例
G=[0 0 10 0 30 100;0 0 5 0 0 0;0 0 0 50 0 0;0 0 0 0 0 10;0 0 0 20 0 60;0 0 0 0 0 0];
%% 無向圖範例
G=[0 0 10 0 30 100;
0 0 5 0 0 0;
10 5 0 50 0 0;
0 0 50 0 20 10;
30 0 0 20 0 60;
100 0 0 10 60 0];
minPath=shortestPath(G,6);
disp('測試完畢');