您好,欢迎访问三七文档
当前位置:首页 > 临时分类 > 最短路径万能Dijkstra算法必备代码
clear;n=input('Pleaseinputthenumberofthenotes:k=');%输入节点数目p=n*n;disp('Note:Ifthereisnodirectlinkbetweennotes,use100toreprsentinfinite');temp=input('Pleaseinputthek*kmatrixofthelengthofpath:M=');%输入路径长度矩阵while(prod(size(temp))~=p)%验证输入矩阵维数是否正确disp('pleaseinputthecorrectsizeofthematrix');temp=input('Pleaseinputthek*kmatrixofthelengthofpath:M=');endw=temp;%路径矩阵初始化i=input('Pleaseidentifytheinitialnote:s=');%输入指定节点[s,d]=Dijkstra_sub(i,n,w)Dijkstra_sub函数代码如下:function[S,D]=Dijkstra_sub(i,m,W)dd=[];tt=[];ss=[];ss(1,1)=i;V=1:m;V(i)=[];dd=[0;i];%dd的第二行是每次求出的最短路径的终点,第一行是最短路径的值kk=2;[mdd,ndd]=size(dd);while~isempty(V)[tmpd,j]=min(W(i,V));tmpj=V(j);fork=2:ndd[tmp1,jj]=min(dd(1,k)+W(dd(2,k),V));tmp2=V(jj);tt(k-1,:)=[tmp1,tmp2,jj];endtmp=[tmpd,tmpj,j;tt];[tmp3,tmp4]=min(tmp(:,1));iftmp3==tmpdss(1:2,kk)=[i;tmp(tmp4,2)];elsetmp5=find(ss(:,tmp4)~=0);tmp6=length(tmp5);ifdd(2,tmp4)==ss(tmp6,tmp4)ss(1:tmp6+1,kk)=[ss(tmp5,tmp4);tmp(tmp4,2)];elsess(1:3,kk)=[i;dd(2,tmp4);tmp(tmp4,2)];end;enddd=[dd,[tmp3;tmp(tmp4,2)]];V(tmp(tmp4,3))=[];[mdd,ndd]=size(dd);kk=kk+1;end;S=ss;D=dd(1,:);
本文标题:最短路径万能Dijkstra算法必备代码
链接地址:https://www.777doc.com/doc-4230111 .html