1、效果展示:开头输入的是点的序列号(表示第几个点) ,显示的是最短路径的走法(同样以点的序列号显示,表示途径的第几个点) 。%编写 m 文件function distance,path=dijkstra(A,s,e)% DISTANCE,PATH=DIJKSTRA(A,S,E)% returns the distance and path between the start node and the end node.% A: adjcent matrix% s: start node% e: end node% initializen=size(A,1); % node numberD=A(s
2、,:); % distance vectorpath=; % path vectorvisit=ones(1,n); % node visibilityvisit(s)=0; % source node is unvisibleparent=zeros(1,n); % parent node% the shortest distancefor i=1:n-1 % BlueSet has n-1 nodestemp=zeros(1,n);count=0;for j=1:nif visit(j)temp=temp(1:count) D(j);elsetemp=temp(1:count) inf;e
3、ndcount=count+1;endvalue,index=min(temp);j=index; visit(j)=0;for k=1:nif D(k)D(j)+A(j,k)D(k)=D(j)+A(j,k);parent(k)=j;endendenddistance=D(e);% the shortest distance pathif parent(e)=0return;endpath=zeros(1,2*n); % path preallocationt=e; path(1)=t; count=1;while t=s path=p path(1:count);t=p;count=coun
4、t+1;endif count=2*nerror(The path preallocation length is too short.,.Please redefine path preallocation parameter.);endpath(1)=s;path=path(1:count);%算法实现clc; clear; close all;% 载入设置数据lines = load(Distance.txt); %点与点之间的距离矩阵A=lines;A(find(A10)=inf; %对步长的限制,根据自己的要求决定!我们在此选择 10.% A 就是连接矩阵,其中对角线为 0,表示本身
5、% 有连接关系的就对应线的长度% 没有连接关系的就对应 inf% 下面的是 dijstra 算法,有两种方式可以调用s =input(输入起点); % 起点(点的序号)e =input(输入终点); % 终点(点的序号)distance,path0 = dijkstra(A,s,e);fprintf(n Use Dijkstra the Min Distance is: %.5f n, distance);fprintf(n Use Dijkstra the Min Distance path is: n);disp(path0);A1 = A;A1(isinf(A1) = 0;d, p, pred = graphshortestpath(sparse(A1), s, e);fprintf(n Use graphshortestpath the Min Distance is: %.5f n, d);fprintf(n Use graphshortestpath the Min Distance path is: n);disp(p);for i = 1 : length(path0)if i = length(path0)temp = path0(1) path0(i);elsetemp = path0(i) path0(i+1);endend