To solve the shortest path problem, of course, you need to think of the BFS:

    public int shortestPathBinaryMatrix(int[][] grid) {
        int[][] dirs = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
        int len = 0;
        Queue<int[]> queue = new LinkedList<>();
        int m = grid.length, n = grid[0].length;
        boolean[][] visited = new boolean[m][n];

        if (grid[0][0] == 0) {
            queue.offer(new int[]{0, 0});
            visited[0][0] = true;
        }

        while (!queue.isEmpty()) {
            int size = queue.size();
            len++;
            for (int i = 0; i < size; i++) {
                int[] node = queue.poll();
                if (node[0] == m - 1 && node[1] == n - 1)
                    return len;
                for (int[] dir : dirs) {
                    int x = node[0] + dir[0];
                    int y = node[1] + dir[1];
                    if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0 && !visited[x][y]) {
                        queue.offer(new int[]{x, y});
                        visited[x][y] = true;
                    }

                }
            }
        }
        return -1;

    }

 

We don't have to use the "visited" variable:

class Solution {
    int[][] dirs={{-1,-1},{-1,0},{-1,1},{1,-1},{1,0},{1,1},{0,-1},{0,1}};
    public int shortestPathBinaryMatrix(int[][] grid) {
        if(grid==null||grid.length==0)
            return 0;
        if(grid[0][0]==1)
            return -1;
        int n = grid.length;
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{0,0});
        grid[0][0]=1;
        int res=1;
        while(!queue.isEmpty()){
            int size = queue.size();                //Don't forget this step
            for(int i=0;i<size;i++){
                int[] cell = queue.poll();
                if(cell[0]==n-1&&cell[1]==n-1)
                    return res;
                for(int[] dir:dirs){
                    int x = cell[0]+dir[0];
                    int y = cell[1]+dir[1];
                    if(x>=0&&x<n&&y>=0&&y<n&&grid[x][y]==0){    //Don't forget check whether x, y is within the grid
                        queue.offer(new int[]{x, y});
                        grid[x][y]=1;
                    }
                }
            }
            res++;   
        }
        return -1;
    }
}

 

posted on 2022-02-02 14:25  阳光明媚的菲越  阅读(20)  评论(0编辑  收藏  举报