访问所有节点的最短路径

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
class Solution {
public:
int shortestPathLength(vector<vector<int>>& graph) {
int n = graph.size();
queue<tuple<int, int, int>> q;
vector<vector<int>> seen(n, vector<int>(1 << n));
for (int i = 0; i < n; i++) {
q.emplace(i, 1 << i, 0);
seen[i][1 << i] = true;
}
int ans = 0;
while (q.size()) {
auto [u, mask, dist] = q.front();
q.pop();
if (mask == (1 << n) - 1) {
ans = dist;
break;
}
for (int v : graph[u]) {
int mask_v = mask | (1 << v);
if (!seen[v][mask_v]) {
q.emplace(v, mask_v, dist + 1);
seen[v][mask_v] = true;
}
}
}
return ans;
}
};