Advertisement
lLab__

LC847: Shortest Path Visiting All Nodes

Dec 1st, 2021
889
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.99 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int shortestPathLength(vector<vector<int>>& graph) {
  4.         int n = graph.size();
  5.         int ed = (1<<n)-1;
  6.        
  7.         vector<vector<int>> vis(ed+1, vector<int>(n, 2e9));
  8.         queue<pair<int, pair<int, int>>> q; // d k u
  9.        
  10.         vis[1][0] = 0;
  11.         q.push({0, {1, 0}});
  12.        
  13.         for(int i=1;i<n;++i){
  14.             if(graph[i].size() > 1) continue;
  15.             vis[1<<i][i] = 0;
  16.             q.push({0, {1<<i, i}});
  17.         }
  18.        
  19.         while(!q.empty()){
  20.             int d = q.front().first;
  21.             int k = q.front().second.first;
  22.             int u = q.front().second.second;
  23.             q.pop();
  24.            
  25.             if(k == ed) return d;
  26.            
  27.             for(auto v:graph[u]){
  28.                 if(vis[k|(1<<v)][v] != 2e9) continue;
  29.                 vis[k|(1<<v)][v] = d+1;
  30.                 q.push({d+1, {k|(1<<v), v}});
  31.             }
  32.         }
  33.        
  34.         return -1; // impossible
  35.     }
  36. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement