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
| public class BitmaskDP {
public static int shortestPath(int n, int[][] dist) { int totalStates = 1 << n;
int[][] dp = new int[n][totalStates]; for (int[] row : dp) { Arrays.fill(row, Integer.MAX_VALUE); } dp[0][1] = 0;
for (int mask = 1; mask < totalStates; mask++) { for (int u = 0; u < n; u++) { if ((mask & (1 << u)) != 0) { for (int v = 0; v < n; v++) { if (v != u && (mask & (1 << v)) != 0) { dp[u][mask] = Math.min(dp[u][mask], dp[v][mask ^ (1 << u)] + dist[v][u]); } } } } }
int minPath = Integer.MAX_VALUE; for (int u = 1; u < n; u++) { minPath = Math.min(minPath, dp[u][totalStates - 1] + dist[u][0]); }
return minPath; }
public static void main(String[] args) { int n = 4; int[][] dist = { {0, 10, 15, 20}, {10, 0, 35, 25}, {15, 35, 0, 30}, {20, 25, 30, 0} };
int shortest = shortestPath(n, dist); System.out.println("Shortest Path: " + shortest); } }
|