图论15(Leetcode1091.二进制矩阵中的最短路径)

答案:

class Solution {
    public int shortestPathBinaryMatrix(int[][] grid) {
        int n = grid.length;
        if(grid[0][0]!=0)return -1;
        if(grid[n-1][n-1]!=0)return -1;
        int step = 0;
        Queue queue = new LinkedList<>();
        int start[] = {0,0};
        queue.add(start);
        while(queue.size()!=0){
            step++;
            int len = queue.size();
            for(int i=0;i=0&&grid[x-1][y]==0){
                    int[] point = {x-1,y};
                    queue.add(point);
                    grid[x-1][y]=-1;
                }
                if(x+1=0&&grid[x][y-1]==0){
                    int[] point = {x,y-1};
                    queue.add(point);
                    grid[x][y-1]=-1;
                }
                if(y+1=0&&grid[x+1][y-1]==0){
                    int[] point = {x+1,y-1};
                    queue.add(point);
                    grid[x+1][y-1]=-1;
                }
                if(x-1>=0&&y+1=0&&y-1>=0&&grid[x-1][y-1]==0){
                    int[] point = {x-1,y-1};
                    queue.add(point);
                    grid[x-1][y-1]=-1;
                }
            }
        }
        return -1;
    }
}

你可能感兴趣的:(图论,矩阵,算法)