-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Sync LeetCode submission - Shortest Path Visiting All Nodes (cpp)
- Loading branch information
1 parent
baa68e3
commit 5bd7170
Showing
1 changed file
with
29 additions
and
0 deletions.
There are no files selected for viewing
29 changes: 29 additions & 0 deletions
29
AC-Submissions/problems/shortest_path_visiting_all_nodes/solution.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
}; |