Advertisement
nikunjsoni

1197-1

May 4th, 2021
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. class Solution {
  2. bool vis[304][304];
  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.         x = abs(x), y = abs(y);
  9.         queue<pair<int, int>> q;
  10.         q.push({0,0});
  11.         vis[0][0] = 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.                     nextX = abs(nextX); nextY = abs(nextY);
  20.                     if(nextX == x && nextY == y)
  21.                         return steps+1;
  22.  
  23.                     if(!vis[nextX][nextY]){
  24.                         vis[nextX][nextY] = true;
  25.                         q.push({nextX, nextY});
  26.                     }
  27.                 }
  28.             }
  29.             steps++;
  30.         }
  31.         return steps;
  32.     }
  33. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement