Dijkstra算法,最短路径路由算法matlab代码
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
-
-
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /boutique/detail/tanhhafgeb
系列文章
更多
同类精品
更多
-
photoshop保存的图片太大微信发不了怎么办
PHP中文网 06-15 -
《学习通》视频自动暂停处理方法
HelloWorld317 07-05 -
word里面弄一个表格后上面的标题会跑到下面怎么办
PHP中文网 06-20 -
Android 11 保存文件到外部存储,并分享文件
Luke 10-12 -
photoshop扩展功能面板显示灰色怎么办
PHP中文网 06-14 -
微信公众号没有声音提示怎么办
PHP中文网 03-31 -
excel下划线不显示怎么办
PHP中文网 06-23 -
excel打印预览压线压字怎么办
PHP中文网 06-22 -
TikTok加速器哪个好免费的TK加速器推荐
TK小达人 10-01 -
怎样阻止微信小程序自动打开
PHP中文网 06-13