【BFS】LeetCode 1091. 二进制矩阵中的最短路径

题目链接

1091. 二进制矩阵中的最短路径

思路

BFS 找最短路模板题

代码

class Solution {
    public int shortestPathBinaryMatrix(int[][] grid) {
        if(grid[0][0] == 1 || grid[grid.length - 1][grid[0].length - 1] == 1){
            return -1;
        }

        Queue<Pair<Pair<Integer, Integer>, Integer>> queue = new LinkedList<>();
        boolean[][] visited = new boolean[grid.length][grid[0].length];

        queue.offer(new Pair<>(new Pair<>(0, 0), 1));
        int[] dx = new int[]{1, 0, -1, 0, 1, 1, -1, -1};
        int[] dy = new int[]{0, 1, 0, -1, 1, -1, 1, -1};
        while(!queue.isEmpty()){
            Pair<Pair<Integer, Integer>, Integer> currentState = queue.remove();
            int currentStep = currentState.getValue();
            Pair<Integer, Integer> currentPos = currentState.getKey();
            if(currentPos.getKey() == grid.length - 1 && currentPos.getValue() == grid[0].length - 1){
                return currentStep;
            }

            for(int i = 0; i < 8; i++){
                int nextX = currentPos.getKey() + dx[i];
                int nextY = currentPos.getValue() + dy[i];

                if(valid(nextX, nextY, visited, grid)){
                    queue.offer(new Pair<>(new Pair<>(nextX, nextY), currentStep + 1));
                    visited[nextX][nextY] = true;
                }
            }
        }

        return -1;
    }

    private boolean valid(int nextX, int nextY, boolean[][] visited, int[][] grid) {
        return (
                0 <= nextX && nextX < grid.length && 0 <= nextY && nextY < grid[0].length &&
                        !visited[nextX][nextY] && grid[nextX][nextY] == 0
                );
    }
}
posted @   Frodo1124  阅读(45)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
点击右上角即可分享
微信分享提示