nikunjsoni

818-1

May 26th, 2021
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     struct state{
  4.         int speed, position;
  5.         state(int s, int pos){
  6.             speed = s;
  7.             position = pos;
  8.         }
  9.     };
  10.    
  11.     int racecar(int target) {
  12.         queue<state> q;
  13.         unordered_map<string, bool> vis;
  14.         int distance = 0;
  15.         q.push(state(1, 0));
  16.         vis["1,0"] = true;
  17.        
  18.         // BFS on next states.
  19.         while(!q.empty()){
  20.             int size = q.size();
  21.             for(int i=0; i<size; i++){
  22.                 state cur = q.front(); q.pop();
  23.                 if(cur.position == target)
  24.                     return distance;
  25.                
  26.                 // Next move is A
  27.                 int nextPos = cur.position+cur.speed;
  28.                 int nextSpeed = cur.speed*2;
  29.                 if(nextPos == target)
  30.                     return distance+1;
  31.                 string nextState = to_string(nextSpeed)+","+to_string(nextPos);
  32.                 if(!vis.count(nextState) && abs(nextPos-target) < target){
  33.                     vis[nextState] = true;
  34.                     q.push(state(nextSpeed, nextPos));
  35.                 }
  36.                
  37.                 // Next move is R
  38.                 nextPos = cur.position;
  39.                 nextSpeed = (cur.speed > 0) ? -1 : 1;
  40.                 if(nextPos == target)
  41.                     return distance+1;
  42.                 nextState = to_string(nextSpeed)+","+to_string(nextPos);
  43.                 if(!vis.count(nextState) && abs(nextPos-target) < target){
  44.                     vis[nextState] = true;
  45.                     q.push(state(nextSpeed, nextPos));
  46.                 }
  47.             }
  48.             distance++;
  49.         }
  50.         return -1;
  51.     }
  52. };
Advertisement
Add Comment
Please, Sign In to add comment