forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.cpp
35 lines (33 loc) · 1.04 KB
/
Solution2.cpp
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
class Solution {
public:
int n;
int shortestPathLength(vector<vector<int>>& graph) {
n = graph.size();
priority_queue<tuple<int, int, int>, vector<tuple<int, int, int>>, greater<tuple<int, int, int>>> q;
vector<vector<int>> dist(n, vector<int>(1 << n, INT_MAX));
for (int i = 0; i < n; ++i) {
q.push({f(1 << i), i, 1 << i});
dist[i][1 << i] = 0;
}
while (!q.empty()) {
auto [_, u, state] = q.top();
q.pop();
if (state == (1 << n) - 1) return dist[u][state];
for (int v : graph[u]) {
int nxt = state | (1 << v);
if (dist[v][nxt] > dist[u][state] + 1) {
dist[v][nxt] = dist[u][state] + 1;
q.push({dist[v][nxt] + f(nxt), v, nxt});
}
}
}
return 0;
}
int f(int state) {
int ans = 0;
for (int i = 0; i < n; ++i)
if (((state >> i) & 1) == 0)
++ans;
return ans;
}
};