Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- int shortestPathLength(vector<vector<int>>& graph) {
- int n = graph.size();
- bool vis[1<<n][n];
- memset(vis, 0, sizeof vis);
- queue<pair<int, int>> q;
- int mask = 0;
- // Special case of 1 node.
- if(graph.size() == 1) return 0;
- // Assume (mask of visited, current node) as state of BFS.
- // Push initial states in queue.
- for(int i=0; i<graph.size(); i++){
- int newMask = mask | (1<<i);
- q.push({newMask, i});
- vis[newMask][i] = true;
- }
- int steps = 0;
- while(!q.empty()){
- int sz = q.size();
- for(int i=0; i<sz; i++){
- auto p = q.front(); q.pop();
- int mask = p.first, node = p.second;
- // Push new states in queue if not visited.
- for(auto child: graph[node]){
- int newMask = mask | (1<<child);
- if(newMask == ((1<<graph.size())-1))
- return steps+1;
- if(vis[newMask][child]) continue;
- q.push({newMask, child});
- vis[newMask][child] = true;
- }
- }
- steps++;
- }
- return steps;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement