Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- using pi = pair <int, int>;
- using pii = pair <int, pi>;
- int shortestPathLength(vector<vector<int>> &graph){
- int n = graph.size();
- vector <int> g[n];
- for(int u=0;u<=n-1;u++){
- for(auto v: graph[u]){
- g[u].push_back(v);
- }
- }
- int Bit = (1 << n) - 1;
- vector < vector <int> > dis(n, vector <int> (Bit + 1, 1e9));
- vector < vector <bool> > vs(n, vector <bool> (Bit + 1, false));
- queue <pii> q;
- for(int u=0;u<=n-1;u++){
- dis[u][1 << u] = 0;
- q.push({0, {u, 1 << u}});
- }
- while(!q.empty()){
- int d = q.front().first;
- int u = q.front().second.first;
- int bit = q.front().second.second;
- q.pop();
- if(vs[u][bit]) continue; vs[u][bit] = true;
- if(bit == Bit) return d;
- for(auto v: g[u]){
- int nxtbit = bit | (1 << v);
- if(!vs[v][nxtbit] and 1 + d < dis[v][nxtbit]){
- dis[v][nxtbit] = d + 1;
- q.push({d + 1, {v, nxtbit}});
- }
- }
- }
- return -1;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement