You have an undirected, connected graph of n nodes labeled from 0 to n - 1. You are given an array graph where graph[i] is a list of all the nodes connected with node i by an edge.
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.
We need the shortest path that visits all nodes in a graph. Since revisiting nodes is allowed, and the number of nodes is small, we can use BFS with a bitmask to track visited nodes. Each state is defined by the current node and the set of visited nodes.
classSolution {
publicintshortestPathLength(int[][] graph) {
int n = graph.length;
Queue<int[]> q =new LinkedList<>();
boolean[][] vis =newboolean[n][1<<n];
for (int i = 0; i < n; i++) {
q.offer(newint[]{i, 1<<i});
vis[i][1<<i]=true;
}
int ans = 0;
while (!q.isEmpty()) {
int sz = q.size();
for (int i = 0; i < sz; i++) {
int[] cur = q.poll();
int u = cur[0], mask = cur[1];
if (mask == (1<<n)-1) return ans;
for (int v : graph[u]) {
int nxt = mask | (1<<v);
if (!vis[v][nxt]) {
vis[v][nxt]=true;
q.offer(newint[]{v, nxt});
}
}
}
ans++;
}
return-1;
}
}
classSolution {
funshortestPathLength(graph: Array<IntArray>): Int {
val n = graph.size
val vis = Array(n) { BooleanArray(1 shl n) }
val q = ArrayDeque<Pair<Int, Int>>()
for (i in0 until n) {
q.add(i to (1 shl i))
vis[i][1 shl i] = true }
var ans = 0while (q.isNotEmpty()) {
repeat(q.size) {
val(u, mask) = q.removeFirst()
if (mask == (1 shl n) - 1) return ans
for (v in graph[u]) {
val nxt = mask or (1 shl v)
if (!vis[v][nxt]) {
vis[v][nxt] = true q.add(v to nxt)
}
}
}
ans++ }
return -1 }
}
defshortestPathLength(graph: list[list[int]]) -> int:
n = len(graph)
from collections import deque
vis = [[False]*(1<<n) for _ in range(n)]
q = deque((i, 1<<i) for i in range(n))
for i in range(n):
vis[i][1<<i] =True ans =0while q:
for _ in range(len(q)):
u, mask = q.popleft()
if mask == (1<<n)-1:
return ans
for v in graph[u]:
nxt = mask | (1<<v)
ifnot vis[v][nxt]:
vis[v][nxt] =True q.append((v, nxt))
ans +=1return-1