- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
java解法
使用动态规划结合状态压缩来解决问题。
定义 dp[u][mask] 表示当前在点
𝑢
u,访问过的点集合为 mask 时的最短路径长度。
通过逐步扩展访问点的集合,从只访问起点
0
0 开始,逐步扩展到访问所有点。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] dist = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
dist[i][j] = sc.nextInt();
}
}
System.out.println(tsp(dist, n));
}
public static int tsp(int[][] dist, int n) {
int[][] dp = new int[n][1 << n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < (1 << n); j++) {
dp[i][j] = Integer.MAX_VALUE / 2;
}
}
dp[0][1] = 0;
for (int mask = 1; mask < (1 << n); mask++) {
for (int u = 0; u < n; u++) {
if ((mask & (1 << u)) != 0) {
for (int v = 0; v < n; v++) {
if ((mask & (1 << v)) == 0) {
dp[v][mask | (1 << v)] = Math.min(
dp[v][mask | (1 << v)],
dp[u][mask] + dist[u][v]
);
}
}
}
}
}
int result = Integer.MAX_VALUE;
for (int i = 1; i < n; i++) {
result = Math.min(result, dp[i][(1 << n) - 1] + dist[i][0]);
}
return result;
}
}
class="hljs-button signin active" data-title="登录复制" data-report-click="{"spm":"1001.2101.3001.4334"}">
评论记录:
回复评论: