This commit is contained in:
2025-03-26 20:08:20 +08:00
commit f868afc84c
5 changed files with 109 additions and 0 deletions

23
calculateDistanceMatrix.m Normal file
View File

@@ -0,0 +1,23 @@
function adjacencyMatrix = calculateDistanceMatrix(positions)
% 线
% positions - (n3)
% adjacencyMatrix - n×n
%
numCities = size(positions, 1);
%
adjacencyMatrix = zeros(numCities, numCities);
%
for i = 1:numCities
for j = 1:numCities
if i ~= j
%
dx = positions(i, 2) - positions(j, 2);
dy = positions(i, 3) - positions(j, 3);
adjacencyMatrix(i, j) = sqrt(dx^2 + dy^2);
end
end
end
end

24
calculateTourDistance.m Normal file
View File

@@ -0,0 +1,24 @@
function [route, totalDistance] = calculateTourDistance(adjacencyMatrix, startCity)
%
% adjacencyMatrix -
% startCity -
% route -
% totalDistance -
numCities = size(adjacencyMatrix, 1);
%
otherCities = setdiff(1:numCities, startCity);
%
otherCities = otherCities(randperm(length(otherCities)));
%
route = [startCity, otherCities, startCity];
%
totalDistance = 0;
for i = 1:length(route)-1
totalDistance = totalDistance + adjacencyMatrix(route(i), route(i+1));
end
end

22
main.m Normal file
View File

@@ -0,0 +1,22 @@
%
load('postion_att48.mat');
% positions
%
distMatrix = calculateDistanceMatrix(postion);
%
disp(':');
disp(distMatrix);
% 1
startCity = 1;
%
[route, totalDistance] = calculateTourDistance(distMatrix, startCity);
%
fprintf('%d: %.2f\n', startCity, totalDistance);
%
plotTour(postion, route);

40
plotTour.m Normal file
View File

@@ -0,0 +1,40 @@
function plotTour(positions, route)
%
% positions -
% route -
%
figure;
%
plot(positions(:, 2), positions(:, 3), 'o', 'MarkerSize', 8, 'MarkerFaceColor', 'blue');
hold on;
% 线
for i = 1:length(route)-1
current = route(i);
next = route(i+1);
% 线
line([positions(current, 2), positions(next, 2)], ...
[positions(current, 3), positions(next, 3)], ...
'Color', 'red', 'LineWidth', 1.5);
end
%
plot(positions(route(1), 2), positions(route(1), 3), 'gs', 'MarkerSize', 12, 'MarkerFaceColor', 'green');
%
for i = 1:size(positions, 1)
text(positions(i, 2), positions(i, 3), num2str(i), ...
'HorizontalAlignment', 'left', 'VerticalAlignment', 'bottom');
end
%
xlabel('X');
ylabel('Y');
title('');
grid on;
legend('', '', '/');
hold off;
end

BIN
postion_att48.mat Normal file

Binary file not shown.