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

 
 

  • 2
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jubobolv369

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值