Dijkstra算法是一种最短路径路由算法,用于计算一个节点到其他所有节点的最短路径。主要特点是以起始点为中心向外层层扩展,直到扩展到终点为止。
Dijkstra算法能得出最短路径的最优解,但由于它遍历计算的节点很多,所以效率较低。
算法详细解释各网站都有,不太难。下边是对下图从D开始到A节点寻找最短路径的matlab代码,个人原创。
%% Dijkstra算法
%by Jubobolv369 at 2022/1/22
clc;
clear;
close all;
%% 初始化带权邻接矩阵,起点、终点等
initRoute=[0 12 inf inf inf 16 14;
12 0 10 inf inf 7 inf;
inf 10 0 3 5 6 inf;
inf inf 3 0 4 inf inf;
inf inf 5 4 0 2 8;
16 7 6 inf 2 0 9;
14 inf inf inf 8 9 0;];
[row,column]=size(initRoute);
start_node=4;
end_node=1;
close_list=[];
open_list=[];
%closelist中加入初始节点
close_list=[start_node,start_node,0];
%% 如果closelist中没有终点,则遍历节点,通过比较逐渐加入节点到closelist。
while isempty(find(close_list(:,1) == end_node))
[last1,~]=size(close_list);%获取closelist的最后一行的索引
now_node=close_list(last1,1);%当前节点编号
now_length=close_list(last1,3);%当前最优长度
[last2,~]=size(open_list); %%获取openlist的最后一行的索引
now_list=initRoute(now_node,:); %从原始矩阵中取初当前节点的边权值
i=1;
%% 更新openlist
for j=1:column
%如果第j个节点可达、不是自身且不在close_list中,该点可能需要改动或添加到openlist中
if now_list(j)~=inf && now_list(j)~=0 && isempty(find(close_list(:,1) == j))
if last1==1
open_list(i,1)=j;
open_list(i,2)=now_node;
open_list(i,3)=now_list(j);
i=i+1;
%如果不在openlist中,就将其添加到其中,否则将通过当前父节点到此节点的权值与之前的作比较
else
k=find(open_list(:,1) == j);
if isempty(k)
open_list(last2+i,1)=j;
open_list(last2+i,2)=now_node;
open_list(last2+i,3)=now_list(j)+now_length;
i=i+1;
elseif open_list(k,3)>(now_list(j)+now_length) %若現在的路徑長度小,則更新路徑
open_list(k,1)=j;
open_list(k,2)=now_node;
open_list(k,3)=now_list(j)+now_length;
end
end
end
end
%% 更新closelist和openlist。将openlist里路径最小值的行放入closelist中
[min_value,index]=min(open_list(:,3));
close_list=[close_list; open_list(index,:)];
open_list(index,:)=[];
end
%% 反找出最优路径及路径长度
path_op=[end_node];
index=find(close_list(:,1) == end_node);
path_length=close_list(index,3)
while isempty(find(path_op==start_node))
path_op=[path_op close_list(index,2)];
index=find(close_list(:,1) == close_list(index,2))
end
path_op