主程序
clear;clc;
B=1+round(4*rand(4));
for i=1:4;
for j=1:4;
if i<=j;
B(i,j)=0;
end
end
end
B=B'+B;%设一个随机的邻接矩阵
for x=1:100
MIN=min(min(B));
if MIN==0;
B(find(B==0))=inf;
MIN=min(min(B));
end
if min(min(B))==max(max(B))%在矩阵中只有最大值时停止
ruture
end
[i,j]=find(B==MIN);
B(i,j)=inf;%删去负载最小的边
long=size(i,2);
wide=size(i,1);
if long>wide
for s=1:long
start=i(s);
terminal=i(s+long);
w=B;
[min,path]=pruning3(w,start,terminal);%求最短路径
eval(['min',int2str(s),'=min']);
eval(['path',int2str(s),'=path']);
end
else
for s=1:wide/2;
start=i(s);
terminal=i(s+wide/2);
w=B;
[min,path]=pruning3(w,start,terminal);
eval(['min',int2str(s),'=min']);
eval(['path',int2str(s),'=path']);
end
end
for i=1:s
eval(['A{i}={path',num2str(i),'};']);
end
for n=1:s
E=cell2mat(A{n});
for m=1:(length(E)-1)
B(E(m),E(m+1))= B(E(m),E(m+1))+MIN;%重新分配
B(E(m+1),E(m))= B(E(m+1),E(m))+MIN;
end
end
B(find(B==inf))=0;
B
clearvars -EXCEPT B
end
最短路径程序
function [min,path]=pruning3(w,start,terminal)
n=size(w,1);%邻接矩阵的长
label(start)=0;%标记开始顶点为 0
f(start)=start;
for i=1:n%先标记四个节点
if i~=start
label(i)=inf;
end
end
s(1)=start; u=start;
while length(s)
for i=1:n
ins=0;
for j=1:length(s)
if i==s(j)
ins=1;
end
end
if ins==0
v=i;
if (u==0)
pause
end
if label(v)>(label(u)+w(u,v))
label(v)=(label(u)+w(u,v));
f(v)=u;
end
end
end
v1=0;
k=inf;
for i=1:n
ins=0;
for j=1:length(s)
if i==s(j)
ins=1;
end
end
if ins==0
v=i;
if k>label(v)
k=label(v); v1=v;
end
end
end
s(length(s)+1)=v1;
u=v1;
end
min=label(terminal); path(1)=terminal;
i=1;
while path(i)~=start
path(i+1)=f(path(i));
i=i+1 ;
end
path(i)=start;
L=length(path);
path=path(L:-1:1);
下标索引必须为正整数类型或逻辑类型。
出错 pruning3 (line 53)
path(i+1)=f(path(i));
出错 pruning2 (line 38)
[min,path]=pruning3(w,start,terminal);