TSP问题(旅行商问题)
TSP问题(旅行商问题)是指旅行家要旅行n个城市,要求各个城市经历且仅经历一次然后回到出发城市,并要求所走的路程最短。
引用一篇博客中对TSP问题的说明https://blog.csdn.net/joekwok/article/details/4749713
用Matlab 对该算法进行说明。
算法很简单,具有通用性,关键是原理要弄清楚。
%%%%初始化各个参数
%穷举法,用于解决简单的TSP问题
c =[0 3 6 7; 5 0 2 3; 6 4 0 2; 3 7 5 0];
s=[1,2,3,4]; %代表目的地个数
d=distance(c,s);
fprintf('最小代价为:');
fprintf('%d',d);
function min_distance =distance(c,s)
L=length(s);
%perms给出集合的全排列
line_component=(perms(s(2:L)));
N=length(line_component);
d=zeros(N,1);
for i=1:N
x=line_component(i,1);
y=line_component(i,L-1);
d(i) = c(1,x) + c(y,1); %底层和顶层初始化
end
for i=1:N
for j=1:L-2
d(i) = d(i) + c(line_component(i,j),line_component(i,j+1));
end
end
min_distance = d(1);
index=1;
for i=2:N
if(d(i)<min_distance)
index=i;
min_distance =d(i);
end
end
fprintf('路线为:1');
for i=1:L-1
fprintf('->');
fprintf('%3d',line_component(index,i));
end
fprintf('->');
fprintf('%3d ',1);
fprintf('\n');