TSP问题的贪婪算法
教材上有算法的文字表述,我只是用MatLab实现了一下:
%tsp2
clc;clear;
format short;
n=input('n=');
%生成路程矩阵
tic;
D=fload('D.dat',n,n+1);
f=zeros(1,n);
for K=1:n;
N=1:1:n;
N=exclude(N,K);
P=[K];
k=K;
while 1==1
[d k0]=min(D(k,N));
f(k)=f(k)+d;
k0=N(k0);
P=append(P,k0);
if size(P,2)==n
break;
else
k=k0;
N=exclude(N,k0);
end
end
PP(K,:)=P;
f(K)=f(K)+D(N,K);%back to start
end
[ff l]=min(f);
PP(l,:)
ff
toc
里面还用到几个自定义函数,见名知义,不解释了。
function makeD()
clear;clc;
n=input('n=');
D=random('Normal',100,31,n,n);
for k=1:n
D(k,k)=0;
D(k,n+1)=D(k,1);
end
fsave('D.dat',D);
function f=fsave(fn,A)
fid=fopen(fn,'w');
n=size(A,1);%hang
m=size(A,2);%lie
for k=1:n
for l=1:m
fprintf(fid,'%6.4f\t',A(k,l));
end
fprintf(fid,'\n');
end
fclose(fid);
function A=fload(fn,m,n)
fid=fopen(fn,'r');
A=fscanf(fid,'%g',[n m]);
A=A';
fclose(fid);
function Y=exclude(N,x)
Y=[];
for k=1:size(N,2)
if x==N(k)
continue;
else
Y=append(Y,N(k));
end
end
function rt=append(P,x)
P((size(P,2)+1))=x;
rt=P;
function bool=belongTo(P,x)
bool=0;
for k=1:size(P,2)
if x==P(k)
bool=1;
return;
end
end
posted on 2005-09-08 16:03 civ3's .NET studying 阅读(1421) 评论(0) 编辑 收藏 举报