Files
MATLAB3/calculateTourDistance.m
2025-03-26 20:08:20 +08:00

24 lines
898 B
Matlab
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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