An undirected, connected graph of N nodes (labeled 0, 1, 2, ..., N-1
) is given as graph
.
graph.length = N
, and j != i
is in the list graph[i]
exactly once, if and only if nodes i
and j
are connected.
Return the length of the shortest path that visits every node. You may start and stop at any node, you may revisit nodes multiple times, and you may reuse edges.
Example 1:
Input: [[1,2,3],[0],[0],[0]] Output: 4 Explanation: One possible path is [1,0,2,0,3]
Example 2:
Input: [[1],[0,2,4],[1,3,4],[2],[1,2]] Output: 4 Explanation: One possible path is [0,1,4,2,3]
Note:
1 <= graph.length <= 12
0 <= graph[i].length < graph.length
Because each edge has the same weight, the shortest path can be solution by using BFS, and the access of the point can be recorded by state compression.
class Solution:
def shortestPathLength(self, graph: List[List[int]]) -> int:
n = len(graph)
dst = -1 ^ (-1 << n)
q = deque()
vis = [[False] * (1 << n) for _ in range(n)]
for i in range(n):
q.append((i, 1 << i, 0))
vis[i][1 << i] = True
while q:
u, state, dis = q.popleft()
for v in graph[u]:
nxt = state | (1 << v)
if nxt == dst:
return dis + 1
if not vis[v][nxt]:
q.append((v, nxt, dis + 1))
vis[v][nxt] = True
return 0
class Solution {
public int shortestPathLength(int[][] graph) {
int n = graph.length;
int dst = -1 ^ (-1 << n);
Queue<Tuple> queue = new ArrayDeque<>();
boolean[][] vis = new boolean[n][1 << n];
for (int i = 0; i < n; i++) {
queue.offer(new Tuple(i, 1 << i, 0));
vis[i][1 << i] = true;
}
while (!queue.isEmpty()) {
Tuple t = queue.poll();
int u = t.u, state = t.state, dis = t.dis;
for (int v : graph[u]) {
int next = state | (1 << v);
if (next == dst) {
return dis + 1;
}
if (!vis[v][next]) {
queue.offer(new Tuple(v, next, dis + 1));
vis[v][next] = true;
}
}
}
return 0;
}
private static class Tuple {
int u;
int state;
int dis;
public Tuple(int u, int state, int dis) {
this.u = u;
this.state = state;
this.dis = dis;
}
}
}
type tuple struct {
u int
state int
dis int
}
func shortestPathLength(graph [][]int) int {
n := len(graph)
dst := -1 ^ (-1 << n)
q := make([]tuple, 0)
vis := make([][]bool, n)
for i := 0; i < n; i++ {
vis[i] = make([]bool, 1<<n)
q = append(q, tuple{i, 1 << i, 0})
vis[i][1<<i] = true
}
for len(q) > 0 {
t := q[0]
q = q[1:]
cur, state, dis := t.u, t.state, t.dis
for _, v := range graph[cur] {
next := state | (1 << v)
if next == dst {
return dis + 1
}
if !vis[v][next] {
q = append(q, tuple{v, next, dis + 1})
vis[v][next] = true
}
}
}
return 0
}