Minimum Knight Moves

In an infinite chess board with coordinates from -infinity to +infinity, you have a knight at square [0, 0].

A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.

Return the minimum number of steps needed to move the knight to the square [x, y]. It is guaranteed the answer exists.

Example 1:

Input: x = 2, y = 1
Output: 1
Explanation: [0, 0] → [2, 1]

Example 2:

Input: x = 5, y = 5
Output: 4
Explanation: [0, 0] → [2, 1] → [4, 2] → [3, 4] → [5, 5]

思路:x,y abs之后,四个象限可以变成求一个象限的step,因为全部对称。注意>= -1, >=-1是因为第一象限(1,1)这个点,是不能reach的,如果可以变成负数,就可以reach,所以这里是特殊情况,我觉得面试的时候,面试官应该提醒这个吧,否则没人知道。

class Solution {
    public int minKnightMoves(int x, int y) {
        x = Math.abs(x);
        y = Math.abs(y);
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{0,0});
        int[][] dirs = {{2, 1}, {1, 2}, {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, {1, -2}, {2, -1}};
        
        int step = 0;
        HashSet<String> visited = new HashSet<>();
        visited.add("0,0");
        while(!queue.isEmpty()) {
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                int[] node = queue.poll();
                if(node[0] == x && node[1] == y) {
                    return step;
                }
                for(int[] dir: dirs) {
                    int nx = node[0] + dir[0];
                    int ny = node[1] + dir[1];
                    if(!visited.contains(nx + "," + ny) && nx >= -1 && ny >= -1) {
                        visited.add(nx + "," + ny);
                        queue.offer(new int[] {nx, ny});
                    }
                }
            }
            step++;
        }
        return -1;
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值