``` java package com.wm.course.utils; import java.util.ArrayList; import java.util.List; public class TSP { // 距离矩阵 private static final int[][] distances = { {0, 7, 10, 5, 10}, {7, 0, 10, 7, 10}, {10, 10, 0, 6, 8}, {5, 7, 6, 0, 9}, {10, 10, 8, 9, 0} }; // 地点数量 private static final int N = distances.length; // 保存最短路径 private static List shortestPath = new ArrayList(); // 保存最短路径的距离 private static int shortestDistance = Integer.MAX_VALUE; public static void main(String[] args) { List path = new ArrayList(); path.add(0); // 从A开始 boolean[] visited = new boolean[N]; visited[0] = true; tsp(path, visited, 0, 0); System.out.println("最短路径: " + shortestPath); System.out.println("最短距离: " + shortestDistance); } private static void tsp(List path, boolean[] visited, int currentCity, int currentDistance) { if (path.size() == N) { // 回到起点A currentDistance += distances[currentCity][0]; if (currentDistance (path); shortestPath.add(0); // 添加起点A } return; } for (int city = 0; city < N; city++) { if (!visited[city]) { visited[city] = true; path.add(city); tsp(path, visited, city, currentDistance + distances[currentCity][city]); path.remove(path.size() - 1); visited[city] = false; } } } } ```