Advertisement
nikunjsoni

752

Apr 30th, 2021
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     int openLock(vector<string>& deadends, string target) {
  4.         vector<bool> vis(10000, false);
  5.         for(string &str: deadends)
  6.             vis[stoi(str)] = true;
  7.        
  8.         queue<string> q;
  9.         string start = "0000";
  10.         if(!vis[stoi(start)]){
  11.             q.push(start);
  12.             vis[stoi(start)] = true;
  13.         }
  14.        
  15.         int steps = 0;
  16.         if(start == target) return steps;
  17.         while(!q.empty()){
  18.             int sz = q.size();
  19.             for(int i=0; i<sz; i++){
  20.                 string current = q.front();
  21.                 q.pop();
  22.                
  23.                 for(int i=0; i<4; i++){
  24.                     string next = current;
  25.                     next[i] = ((next[i]-'0')+1)%10 + '0';
  26.                     if(!vis[stoi(next)]){
  27.                         q.push(next);
  28.                         vis[stoi(next)] = true;
  29.                         if(next == target)
  30.                             return steps+1;
  31.                     }
  32.                     next = current;
  33.                     next[i] = ((next[i]-'0')-1+10)%10 + '0';
  34.                     if(!vis[stoi(next)]){
  35.                         q.push(next);
  36.                         vis[stoi(next)] = true;
  37.                         if(next == target)
  38.                             return steps+1;
  39.                     }
  40.                 }
  41.             }
  42.             steps++;
  43.         }
  44.         return -1;
  45.     }
  46. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement