旅行商问题
题目:旅行商问题
给 n
个城市(从 1
到 n
),城市和无向道路成本
之间的关系为3元组 [A, B, C]
(在城市 A
和城市 B
之间有一条路,成本是 C
)我们需要从1开始找到的旅行所有城市的付出最小的成本。
一个城市只能通过一次。
你可以假设你可以到达所有的城市
示例:
输入:
n = 3
tuple = [[1,2,1],[2,3,2],[1,3,3]]
输出: 3
说明:最短路是1->2->3
题解:DFS
public class Solution {
class Edge {
int end;
int cost;
public Edge(int end, int cost) {
this.end = end;
this.cost = cost;
}
}
private int minCost;
public void dfs(int city, Map<Integer, List<Edge>> mapper, int cityCount, int cost, int[] visited) {
if (cityCount == visited.length - 1) {
minCost = Math.min(minCost, cost);
}
//最优剪枝
if (cost > minCost) {
return;
}
for (Edge edge : mapper.get(city)) {
if (visited[edge.end] == 1) {
continue;
}
visited[edge.end] = 1;
dfs(edge.end, mapper, cityCount + 1, cost + edge.cost, visited);
visited[edge.end] = 0;
}
}
public int minCost(int n, int[][] roads) {
Map<Integer, List<Edge>> mapper = new HashMap<>();
int[] visited = new int[n + 1];
minCost = 100000000;
if (n == 0) {
return minCost;
}
//建图
for (int i = 1; i <= n; i++) {
mapper.put(i, new ArrayList<>());
}
for (int i = 0; i < roads.length; i++) {
mapper.get(roads[i][0]).add(new Edge(roads[i][1], roads[i][2]));
mapper.get(roads[i][1]).add(new Edge(roads[i][0], roads[i][2]));
}
visited[1] = 1;
dfs(1, mapper, 1, 0, visited);
return minCost;
}
}