Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- bool vis[304][304];
- public:
- int minKnightMoves(int x, int y) {
- int moves[8][2] = {{2,1},{2,-1},{-2,1},{-2,-1},{1,2},{1,-2},{-1,2},{-1,-2}};
- int steps = 0;
- if(x == 0 && y == 0) return 0;
- x = abs(x), y = abs(y);
- queue<pair<int, int>> q;
- q.push({0,0});
- vis[0][0] = true;
- while(!q.empty()){
- int sz = q.size();
- while(sz--){
- auto p = q.front(); q.pop();
- int curX = p.first, curY = p.second;
- for(int i=0; i<8; i++){
- int nextX = curX+moves[i][0], nextY = curY+moves[i][1];
- nextX = abs(nextX); nextY = abs(nextY);
- if(nextX == x && nextY == y)
- return steps+1;
- if(!vis[nextX][nextY]){
- vis[nextX][nextY] = true;
- q.push({nextX, nextY});
- }
- }
- }
- steps++;
- }
- return steps;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement