Advertisement
nikunjsoni

1197

May 4th, 2021
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.02 KB | None | 0 0
  1. class Solution {
  2. bool vis[604][604];
  3. public:
  4.     int minKnightMoves(int x, int y) {
  5.         int moves[8][2] = {{2,1},{2,-1},{-2,1},{-2,-1},{1,2},{1,-2},{-1,2},{-1,-2}};
  6.         int steps = 0;
  7.         if(x == 0 && y == 0) return 0;
  8.        
  9.         queue<pair<int, int>> q;
  10.         q.push({0,0});
  11.         vis[0+300][0+300] = true;
  12.         while(!q.empty()){
  13.             int sz = q.size();
  14.             while(sz--){
  15.                 auto p = q.front(); q.pop();
  16.                 int curX = p.first, curY = p.second;
  17.                 for(int i=0; i<8; i++){
  18.                     int nextX = curX+moves[i][0], nextY = curY+moves[i][1];
  19.                     if(nextX == x && nextY == y)
  20.                         return steps+1;
  21.                    
  22.                     if(!vis[nextX+300][nextY+300]){
  23.                         vis[nextX+300][nextY+300] = true;
  24.                         q.push({nextX, nextY});
  25.                     }
  26.                 }
  27.             }
  28.             steps++;
  29.         }
  30.         return steps;
  31.     }
  32. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement