forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path847.Shortest-Path-Visiting-All-Nodes.cpp
42 lines (37 loc) · 1.14 KB
/
847.Shortest-Path-Visiting-All-Nodes.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
36
37
38
39
40
41
42
class Solution {
public:
int shortestPathLength(vector<vector<int>>& graph)
{
int n = graph.size();
auto visited = vector<vector<bool>>(n,vector<bool>(1<<n,0));
queue<pair<int,int>>q; // {node, visitedNodes}
for (int i=0; i<n; i++)
{
q.push({i, 1<<i});
visited[i][1<<i] = 1;
}
int step = -1;
while(!q.empty())
{
step++;
int len = q.size();
while (len--)
{
int node = q.front().first;
int state = q.front().second;
q.pop();
for (auto& nextNode:graph[node])
{
int nextState = (state | (1<<nextNode));
if (visited[nextNode][nextState]==1)
continue;
if (nextState == (1<<n)-1)
return step+1;
q.push({nextNode, nextState});
visited[nextNode][nextState] = 1;
}
}
}
return 0;
}
};