动态规划 多段图最短路 有向图

本文通过Matlab实现图的构建与可视化,利用Dijkstra算法求解图中两个节点间的最短路径。详细展示了如何创建稀疏矩阵,构建biograph对象,设置节点和边的属性,并使用graphshortestpath函数进行最短路径计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

直接用matlab了。

W = [ 4 1 3 9 8 1 6 7 8 4 7 5 6 8 6 6 5 7 3];
S =  [ 0 0 0 1 1 2 2 2 2 3 3 4 4 5 5 6 6 7 8];S=S+1;
T =  [ 1 2 3 4 5 3 4 5 6 5 6 7 8 7 8 7 8 9 9];T=T+1;
IDS={'u0','u1','u2','u3','u4','u5','u6','u7','u8','u9'};
DG = sparse(S,T,W,10,10);%求稀疏矩阵
bg=biograph(DG,IDS,'ShowArrows','on','ShowWeights','on');%构建biograph对象,设置参数
set(bg.nodes,'shape','circle','color',[1,1,0],'linecolor',[0,0,1]);
set(bg.nodes,'textColor',[0,0,0],'lineWidth',2,'fontsize',9);
set(bg,'EdgeType','straight');%设置连线为直线 
get(bg.nodes,'position');%获取节点位置
dolayout(bg);
bg.nodes(1).position=[6,100];
bg.nodes(2).position=[100,182];
bg.nodes(3).position=[100,100];
bg.nodes(4).position=[100,10];
bg.nodes(5).position=[220,180];
bg.nodes(6).position=[220,104];
bg.nodes(7).position=[220,14];
bg.nodes(8).position=[330,150];
bg.nodes(9).position=[330,50];
bg.nodes(10).position=[460,100];
dolayout(bg,'pathsonly',true);
t = view(bg)
[dist,path,pred] = graphshortestpath(DG,1,10,'directed',true)%Dijkstra求最短路

 

这是多加了条显示路径的语句,就是更好看些了:

W = [ 4 1 3 9 8 1 6 7 8 4 7 5 6 8 6 6 5 7 3];
S =  [ 0 0 0 1 1 2 2 2 2 3 3 4 4 5 5 6 6 7 8];S=S+1;
T =  [ 1 2 3 4 5 3 4 5 6 5 6 7 8 7 8 7 8 9 9];T=T+1;
IDS={'u0','u1','u2','u3','u4','u5','u6','u7','u8','u9'};
DG = sparse(S,T,W,10,10);%求稀疏矩阵
bg=biograph(DG,IDS,'ShowArrows','on','ShowWeights','on');%构建biograph对象,设置参数
set(bg.nodes,'shape','circle','color',[1,1,0],'linecolor',[0,0,1]);
set(bg.nodes,'textColor',[0,0,0],'lineWidth',2,'fontsize',9);
set(bg,'EdgeType','straight');%设置连线为直线 
get(bg.nodes,'position');%获取节点位置
dolayout(bg);
bg.nodes(1).position=[6,100];
bg.nodes(2).position=[100,182];
bg.nodes(3).position=[100,100];
bg.nodes(4).position=[100,10];
bg.nodes(5).position=[220,180];
bg.nodes(6).position=[220,104];
bg.nodes(7).position=[220,14];
bg.nodes(8).position=[330,150];
bg.nodes(9).position=[330,50];
bg.nodes(10).position=[460,100];
dolayout(bg,'pathsonly',true);
[dist,path,pred] = graphshortestpath(DG,1,10,'directed',true)%Dijkstra求最短路
set(bg.nodes(path),'Color',[1 0.4 0.4])
edges=getedgesbynodeid(bg,get(bg.Nodes(path),'ID'));
set(edges,'LineColor',[1 0 0])
set(edges,'LineWidth',1.5)
t = view(bg)

   

转载于:https://www.cnblogs.com/zxhyxiao/p/9320444.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值