力扣1197 进击的骑士 双端BFS

https://leetcode-cn.com/problems/minimum-knight-moves/

class Solution {
    private int mov[][] = {{-2,1},{2,1},{2,-1},{-2,-1},
                            {1,-2},{1,2},{-1,2},{-1,-2}};

    public int minKnightMoves(int x, int y) {
        Queue<int[]> queue0 = new LinkedList<int[]>();
        Queue<int[]> queue1 = new LinkedList<int[]>();
        HashMap<Integer, Integer> map0 = new HashMap<>();    //从起点出发
        HashMap<Integer, Integer> map1 = new HashMap<>();    //从终点出发

        queue0.add(new int[] {0,0});
        queue1.add(new int[] {x,y});
        map0.put(0, 0);
        map1.put(x * 1000 + y, 0);     //x*1000+y自己定义的位置hashcode

        while (map0.size() > 0 || map1.size() > 0) {
            int siz = queue0.size();

            while (siz-- > 0) {
                int cur[] = queue0.poll();
                int curHash = cur[0] * 1000 + cur[1];
                int curStep = map0.get(curHash);

                if (map1.containsKey(curHash)) {
                    return map0.get(curHash) + map1.get(curHash);
                }

                for (int i = 0; i < 8; ++i) {
                    int nx = cur[0] + mov[i][0], ny = cur[1] + mov[i][1];
                    int nHash = nx  * 1000 + ny;

                    if (map0.containsKey(nHash)) {
                        continue;
                    }

                    queue0.add(new int[]{nx, ny});
                    map0.put(nHash, curStep + 1);
                }
            }


            siz = queue1.size();
            while (siz-- > 0) {
                int cur[] = queue1.poll();
                int curHash = cur[0] * 1000 + cur[1];
                int curStep = map1.get(curHash);

                if (map0.containsKey(curHash)) {
                    return map0.get(curHash) + map1.get(curHash);
                }

                for (int i = 0; i < 8; ++i) {
                    int nx = cur[0] + mov[i][0], ny = cur[1] + mov[i][1];
                    int nHash = nx  * 1000 + ny;

                    if (map1.containsKey(nHash)) {
                        continue;
                    }

                    queue1.add(new int[]{nx, ny});
                    map1.put(nHash, curStep + 1);
                }
            }
        }

        return -1;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
今天 12:11
我最近都有点不想活了,天天早10晚11的,还问我爱不爱她目前的状态别说爱谁了,没扇谁就不错了。是不是大家都是一进节子,只有工作没有爱情了
AzureSkies:在字节的时候找的就是字节的,飞书太适合恋爱人士了,能看到是不是已读,是不是在会议中。简直冥婚好伴侣
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务