需求描述:给定一系列城市和每对城市之间的距离,求解访问每一座城市一次并回到起始城市的最短回路。并将该最短回路进行可视化表达。
代码实现:
%%%%%%%%%%%%%%%%%%%%%%%%%% 绘制TSP车辆路径 %%%%%%%%%%%%%%%%%%%%%%%%%%%
%参数Clist:DC+客户坐标
%参数BSF:最优路径
%参数bsf:最优成本值
%参数p:得到最优成本的代数
function drawTSP(Clist,path,bestCost)
hold on %标记DC
for i=2:length(Clist) %标记客户顺序
text(Clist(i,1)+1,Clist(i,2),sprintf('%d',i-1)) %第二个开始为客户
hold on
end
for i=1:length(path)-1 %画路线
x0=Clist(path(i)+1,1);
y0=Clist(path(i)+1,2);
x1=Clist(path(i+1)+1,1);
y1=Clist(path(i+1)+1,2);
xx=[x0,x1];
yy=[y0,y1];
plot(xx,yy,'ms-','LineWidth',2,'MarkerEdgeColor','k','MarkerFaceColor','g')
hold on
end
%连接首尾节点
xheader = Clist(path(1) + 1,1);
yheader = Clist(path(1)+1,2);
xlast = Clist(path(i+1)+1,1);
ylast = Clist(path(i+1)+1,2);
xhl=[xheader,xlast];
yhl=[yheader,ylast];
plot(xhl, yhl, 'ms-','LineWidth',2,'MarkerEdgeColor','k','MarkerFaceColor','g');
title('车辆调度解');
text(15,18,['系统最小成本为 ',num2str(bestCost)]);
hold off;
end
测试代码:
%路径从0开始
serize = [21, 0, 48, 31, 44, 18, 40, 7, 8, 9, 42, 32, 50, 10, 51, 13, 12, 46, 25, 26, 27, 11, 24, 45, 3, 5, 14, 4, 23, 47, 37, 36, 39, 38, 35, 34, 33, 43, 15, 28, 49, 19, 22, 29, 1, 6, 41, 20, 16, 2, 17, 30];
cost = 7685.01;
cities = [
565,575
25,185
345,750
945,685
845,655
880,660
25,230
525,1000
580,1175
650,1130
1605,620
1220,580
1465,200
1530,5
845,680
725,370
145,665
415,635
510,875
560,365
300,465
520,585
480,415
835,625
975,580
1215,245
1320,315
1250,400
660,180
410,250
420,555
575,665
1150,1160
700,580
685,595
685,610
770,610
795,645
720,635
760,650
475,960
95,260
875,920
700,500
555,815
830,485
1170,65
830,610
605,625
595,360
1340,725
1740,245];
drawTSP(cities, serize, cost);
结果展示: