forked from walkccc/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0847.cpp
More file actions
30 lines (27 loc) · 876 Bytes
/
0847.cpp
File metadata and controls
30 lines (27 loc) · 876 Bytes
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
class Solution {
public:
int shortestPathLength(vector<vector<int>>& graph) {
const int n = graph.size();
const int goal = (1 << n) - 1;
queue<pair<int, int>> q;
vector<vector<int>> visited(n, vector<int>(1 << n));
for (int i = 0; i < graph.size(); i++) q.push({i, 1 << i});
int ans = 0;
while (!q.empty()) {
int s = q.size();
while (s--) {
auto p = q.front();
q.pop();
int node = p.first;
int state = p.second;
if (state == goal) return ans;
if (visited[node][state]) continue;
visited[node][state] = 1;
for (int next : graph[node])
q.push({next, state | (1 << next)});
}
ans++;
}
return -1;
}
};