-
Notifications
You must be signed in to change notification settings - Fork 46
/
_847.java
76 lines (67 loc) · 2.03 KB
/
_847.java
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
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Queue;
/**
* LeetCode 847 - Shortest Path Visiting All Nodes
* <p>
* Hamiltonian-path solved by SPFA-style DP
*/
public class _847 {
public int shortestPathLength(int[][] graph) {
int n = graph.length;
int inf = 1 << 29;
int[][] dp = new int[n][1 << n];
for (int[] row : dp) {
Arrays.fill(row, inf);
}
int ans = inf;
Queue<int[]> queue = new ArrayDeque<>();
boolean[][] inQueue = new boolean[n][1 << n];
for (int i = 0; i < n; i++) {
dp[i][1 << i] = 0;
queue.add(new int[]{i, 1 << i});
inQueue[i][1 << i] = true;
}
while (!queue.isEmpty()) {
int u = queue.peek()[0], mask = queue.peek()[1];
queue.poll();
inQueue[u][mask] = false;
if (mask == (1 << n) - 1) {
ans = Math.min(ans, dp[u][mask]);
}
for (int v : graph[u]) {
int newMask = mask | (1 << v);
if (dp[u][mask] + 1 < dp[v][newMask]) {
dp[v][newMask] = dp[u][mask] + 1;
if (!inQueue[v][newMask]) {
inQueue[v][newMask] = true;
queue.add(new int[]{v, newMask});
}
}
}
}
return ans;
}
public static void main(String[] args) {
_847 sol = new _847();
System.out.println(sol.shortestPathLength(new int[][]{
{1, 2, 3},
{0},
{0},
{0},
}));
System.out.println(sol.shortestPathLength(new int[][]{
{1},
{0, 2, 4},
{1, 3, 4},
{2},
{1, 2},
}));
System.out.println(sol.shortestPathLength(new int[][]{
{},
}));
System.out.println(sol.shortestPathLength(new int[][]{
{0},
}));
}
}