-
Notifications
You must be signed in to change notification settings - Fork 3
/
847.cpp
26 lines (26 loc) · 973 Bytes
/
847.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
class Solution {
public:
int shortestPathLength(vector<vector<int>>& graph) {
int n = graph.size();
int target = (1 << n) - 1;
vector<unordered_set<int>> visited(n);
queue<tuple<int, int, int>> q; //node, mask, path length
for (int i = 0; i < n; ++i) {
q.push(make_tuple(i, 1 << i, 0));
visited[i].insert(1 << i);
}
while (!q.empty()) {
auto [node, state, length] = q.front();
q.pop();
if (state == target) return length;
for (auto& neighbor : graph[node]) {
int nextState = state | (1 << neighbor);
if (visited[neighbor].find(nextState) != visited[neighbor].end()) continue;
q.push(make_tuple(neighbor, nextState, length + 1));
visited[neighbor].insert(nextState);
if (nextState == target) return length + 1;
}
}
return -1;
}
};