用产生式得出最短巡查路线的距离的算法是什么?-灵析社区

拽嘻嘻

比如5个地点ABCDE,两两之间可直达,彼此距离也知道,从A出发巡查其他4个地点后回到A,问最短的距离是多少? 我做的是选择题,只有答案,不知道步骤如何来的。 ![](https://wmprod.oss-cn-shanghai.aliyuncs.com/images/20250103/3e20ac1ad744d7a0494d063add9f247d.png)

阅读量:348

点赞量:13

问AI
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; } } } }