资源描述:
《matlab解决最短路径问题代码》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、默认是Dijkstra算法是有权的,我想如果把权都赋1的话,就相当于没权的了参数是带权的稀疏矩阵及结点看看这两个例子(一个有向一个无向),或许你能找到你想知道的%Createadirectedgraphwith6nodesand11edgesW=[.41.99.51.32.15.45.38.32.36.29.21];%这是权DG=sparse([61223445561],[26354163435],W)%有权的有向图h=view(biograph(DG,[],'ShowWeights','on'))
2、%画图,这个好玩%Findshortestpathfrom1to6[dist,path,pred]=graphshortestpath(DG,1,6)%找顶点1到6的最短路径%Markthenodesandedgesoftheshortestpathset(h.Nodes(path),'Color',[10.40.4])%上色edges=getedgesbynodeid(h,get(h.Nodes(path),'ID'));set(edges,'LineColor',[100])%上色set(edg
3、es,'LineWidth',1.5)%上色下面是无向图的例子%%Solvingthepreviousproblemforanundirectedgraph%UG=tril(DG+DG')%h=view(biograph(UG,[],'ShowArrows','off','ShowWeights','on'))%%Findtheshortestpathbetweennode1and6%[dist,path,pred]=graphshortestpath(UG,1,6,'directed',false
4、)%%Markthenodesandedgesoftheshortestpath%set(h.Nodes(path),'Color',[10.40.4])%fowEdges=getedgesbynodeid(h,get(h.Nodes(path),'ID'));%revEdges=getedgesbynodeid(h,get(h.Nodes(fliplr(path)),'ID'));%edges=[fowEdges;revEdges];%set(edges,'LineColor',[100])%se
5、t(edges,'LineWidth',1.5)clc;closeall;clear;loaddata;%globalquyu;quyu=[2,3];%一片区域z_jl=lxjl(jdxx,lxxh);%计算路线的距离z=qyxz(jdxx,quyu,z_jl);%根据节点信息,从z中将y区域的节点和路线选出所有点的信息hzlx(z);%绘制Z的图像[qypt,nqypt]=ptxzm(xjpt,quyu);changdu=length(bhxz(jdxx,1:6));%选出x中y区的标号,只是分区
6、域,求长度并绘制它tt=z(:,[1,2,end])';k=min(min(tt(1:2,:)));%求两次最小值t=tt(1:2,:);xsjz=sparse(t(2,:),t(1,:),tt(3,:),changdu,changdu);%产生稀疏矩阵[dist,path,pred]=zdljxz(xsjz,qypt,k);%三个原包矩阵通过zdljxz计算得到最短路径holdonforj=1:nqyptcolors=rand(1,3);%产生随机数并用颜色标记hzptxc(path{j},jdx
7、x,colors)endholdoffaxisequal%把坐标轴单位设为相等zjd=jdfgd(path,quyu);functionz=lxjl(x,y)%计算路线的距离[mn]=size(y);fori=1:myy(i,1:2)=x(y(i,1),2:3);yy(i,3:4)=x(y(i,2),2:3);endz=sqrt((yy(:,3)-yy(:,1)).^2+(yy(:,2)-yy(:,4)).^2);y=sort(y');y=y';z=[yyyz];z=sortrows(z);func
8、tion[zlz]=ptxz(xjpt,y)pt=xjpt(:,2);wei=ismember(xjpt(:,1),y);z=pt(wei);lz=length(z);unctionhzptxc(path,jdxx,colors)n=length(path);%holdonfori=1:nhzptjd(jdxx,path{i},colors)end%holdoffunctionhzptjd(jdxx,x,colors)%m=length(x);%x=x';holdon