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
| class Solution { private static class State { private final int node; private int visitedMask; private int pathLength;
public State(int node, int visitedMask, int pathLength) { this.node = node; this.visitedMask = visitedMask; this.pathLength = pathLength; } }
public int shortestPathLength(int[][] graph) { int n = graph.length;
boolean[][] nodeVisitedMap = new boolean[n][1 << n]; Queue<State> queue = new LinkedList<>(); for (int i = 0; i < n; i++) { queue.offer(new State(i, 1 << i, 0)); nodeVisitedMap[i][1 << i] = true; }
while (!queue.isEmpty()) { State state = queue.poll(); if (state.visitedMask == (1 << n) - 1) { return state.pathLength; }
for (int nextNode : graph[state.node]) { int mask = state.visitedMask | (1 << nextNode); if (!nodeVisitedMap[nextNode][mask]) { queue.offer(new State(nextNode, mask, state.pathLength + 1)); nodeVisitedMap[nextNode][mask] = true; } } }
return -1; } }
|
References
847. Shortest Path Visiting All Nodes