Skip to content

Commit

Permalink
Sync LeetCode submission - Shortest Path Visiting All Nodes (cpp)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheikh-arman committed Sep 17, 2023
1 parent baa68e3 commit 5bd7170
Showing 1 changed file with 29 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class Solution {
public:
int shortestPathLength(vector<vector<int>>& graph) {
int n = graph.size();
queue<pair<int, int>> q;
vector<vector<bool>> vis(n, vector<bool> (1<<n, false));

for(int i=0; i<n; i++) {
q.push({i, 1<<i});
vis[i][1<<i] = 1;
}
int ans = 0;
while(q.size()) {
for(int k = q.size(); k; k--) {
auto [i, mask] = q.front();
q.pop();
if(mask == (1<<n)-1) return ans;
for(auto x: graph[i]) {
if(!vis[x][mask | (1 << x)]) {
q.push({x, mask | (1 << x)});
vis[x][mask | (1 << x)] = 1;
}
}
}
ans++;
}
return ans;
}
};

0 comments on commit 5bd7170

Please sign in to comment.