摘要
本文主要讲述最短路径算法,一个主要原因是网上的“基于Matlab实现的两点之间最短路径算法”存在各种实现错误,目前为止还没有找到一个完全正确的。所以,本人改正相关错误,上传个正确的版本,即:采用Matlab实现的两点之间Dijkstra(single path)算法。
1. Matlab源文件(dijkstra.m)
function [distance,path]=dijkstra(A,s,e)
%% 参数说明
% 邻接矩阵A
% 起点:s
% 终点:e
% 路径长: distance
% 路径:path
%% 算法主体
n=size(A,1);
D=A(s,:);
path=[];
visit=ones(1,n);
visit(s)=0;
parent=zeros(1,n);
for i=1:n-1
temp=zeros(1,n);
count=0;
for j=1:n
if visit(j)
temp=[temp(1:count) D(j)];
else
temp=[temp(1:count) inf];
end
count=count+1;
end
[value,index]=min(temp);
j=index; visit(j)=0;
for k=1:n
if D(k)>D(j)+A(j,k)
D(k)=D(j)+A(j,k);
parent(k)=j;
end
end
end
%% 结果输出(回溯法)
t = e; %最短路径
while t~=s && t>0
path =[t,path];
p=parent(t);t=p;
end
path =[s,path];
if length(path)==1 % 最短路径长度
distance = A(s,e);
else
distance=D(e);
end
end
2. 测试
>> metrix=[
Inf 1 Inf Inf Inf Inf Inf Inf Inf Inf Inf 1
1 Inf 1 Inf Inf Inf Inf Inf Inf Inf Inf 1
Inf 1 Inf 1 Inf Inf Inf Inf Inf 1 Inf Inf
Inf Inf 1 Inf 1 Inf Inf 1 Inf Inf Inf Inf
Inf Inf Inf 1 Inf 1 Inf Inf Inf Inf Inf Inf
Inf Inf Inf Inf 1 Inf 1 Inf Inf Inf Inf Inf
Inf Inf Inf Inf Inf 1 Inf 1 Inf Inf Inf Inf
Inf Inf Inf 1 Inf Inf 1 Inf 1 1 Inf Inf
Inf Inf Inf Inf Inf Inf Inf 1 Inf Inf Inf Inf
Inf Inf 1 Inf Inf Inf Inf 1 Inf Inf 1 Inf
Inf Inf Inf Inf Inf Inf Inf Inf Inf 1 Inf 1
1 1 Inf Inf Inf Inf Inf Inf Inf Inf 1 Inf]
>> [distance, route]=dijkstra(metrix,1,1)
distance =
Inf
route =
1
>> [distance, route]=dijkstra(metrix,1,2)
distance =
1
route =
1 2
>> [distance, route]=dijkstra(metrix,1,7)
distance =
5
route =
1 2 3 4 8 7