Advertisement
nikunjsoni

847-1

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