Advertisement
nikunjsoni

847

Apr 29th, 2021
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int shortestPathLength(vector<vector<int>>& graph) {
  4.         unordered_map<int, set<int>> vis;
  5.         queue<pair<int, int>> q;
  6.         int mask = 0;
  7.        
  8.         // Special case of 1 node.
  9.         if(graph.size() == 1) return 0;
  10.        
  11.         // Assume (mask of visited, current node) as state of BFS.
  12.         // Push initial states in queue.
  13.         for(int i=0; i<graph.size(); i++){
  14.             int newMask = mask | (1<<i);
  15.             q.push({newMask, i});
  16.             vis[newMask].insert(i);
  17.         }
  18.        
  19.         int steps = 0;
  20.         while(!q.empty()){
  21.             int sz = q.size();
  22.             for(int i=0; i<sz; i++){
  23.                 auto p = q.front(); q.pop();
  24.                 int mask = p.first, node = p.second;
  25.    
  26.                 // Push new states in queue if not visited.
  27.                 for(auto child: graph[node]){
  28.                     int newMask = mask | (1<<child);
  29.                     if(newMask == ((1<<graph.size())-1))
  30.                         return steps+1;
  31.                     if(vis[newMask].count(child)) continue;
  32.                     q.push({newMask, child});
  33.                     vis[newMask].insert(child);
  34.                 }
  35.                
  36.             }
  37.             steps++;
  38.         }
  39.         return steps;
  40.     }
  41. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement