Skip to content

Commit fe89e99

Browse files
authored
Update 847.Shortest-Path-Visiting-All-Nodes.cpp
1 parent b0a4e01 commit fe89e99

1 file changed

Lines changed: 21 additions & 24 deletions

File tree

Lines changed: 21 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,39 @@
11
class Solution {
2+
int visited[12][1<<12];
23
public:
34
int shortestPathLength(vector<vector<int>>& graph)
45
{
5-
int n = graph.size();
6-
auto visited = vector<vector<bool>>(n,vector<bool>(1<<n,0));
7-
8-
queue<pair<int,int>>q; // {node, visitedNodes}
6+
int n=graph.size();
7+
8+
queue<pair<int,int>>q;
9+
910
for (int i=0; i<n; i++)
10-
{
11-
q.push({i, 1<<i});
11+
{
12+
q.push({i,1<<i});
1213
visited[i][1<<i] = 1;
1314
}
14-
15-
int step = -1;
16-
while(!q.empty())
15+
16+
int step = 0;
17+
while (q.size()!=0)
1718
{
18-
step++;
1919
int len = q.size();
2020
while (len--)
2121
{
22-
int node = q.front().first;
23-
int state = q.front().second;
22+
auto [cur, state] = q.front();
2423
q.pop();
2524

26-
for (auto& nextNode:graph[node])
27-
{
28-
int nextState = (state | (1<<nextNode));
29-
if (visited[nextNode][nextState]==1)
30-
continue;
31-
if (nextState == (1<<n)-1)
32-
return step+1;
33-
q.push({nextNode, nextState});
34-
visited[nextNode][nextState] = 1;
35-
}
36-
}
25+
for (int i: graph[cur])
26+
{
27+
if ((state | (1<<i)) == (1<<n)-1) return step+1;
28+
if (visited[i][state]==1) continue;
29+
visited[i][state] = 1;
30+
q.push({i, state | (1<<i)});
31+
}
32+
}
33+
step++;
3734
}
3835

3936
return 0;
40-
4137
}
38+
4239
};

0 commit comments

Comments
 (0)