在一个 N × N 的方形网格中,每个单元格有两种状态:空(0)或者阻塞(1)。
    一条从左上角到右下角、长度为 k 的畅通路径,由满足下述条件的单元格 C1, C_2, …, C_k 组成:
    相邻单元格 C_i 和 C
    {i+1} 在八个方向之一上连通(此时,Ci 和 C{i+1} 不同且共享边或角)
    C_1 位于 (0, 0)(即,值为 grid[0][0])
    C_k 位于 (N-1, N-1)(即,值为 grid[N-1][N-1])
    如果 C_i 位于 (r, c),则 grid[r][c] 为空(即,grid[r][c] == 0)
    返回这条从左上角到右下角的最短畅通路径的长度。如果不存在这样的路径,返回 -1 。
    1091. 二进制矩阵中的最短路径 - 图1


    1091. 二进制矩阵中的最短路径 - 图2
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/shortest-path-in-binary-matrix



    思路:
    找最短路径问题,首先想到的就是BFS,如果是DFS,BFS一层一层往下遍历,找到了就知道下面的是更深层次的,肯定比当前层次的要长
    其次,看到底是八连通还是四连通,就是说斜边能不能走,能走就是八连通,这题就是八连通,还要注意返回值是经过了多少个格子

    1. class Solution {
    2. public int shortestPathBinaryMatrix(int[][] grid) {
    3. //八连通的问题
    4. int[][] DIR = {
    5. {1,0},
    6. {-1,0},
    7. {0,1},
    8. {0,-1},
    9. {1,1},
    10. {1,-1},
    11. {-1,1},
    12. {-1,-1}
    13. };
    14. //定义两个变量来存储长和宽
    15. int R = grid.length;
    16. int C = grid[0].length;
    17. //排除一些特殊情况
    18. if (grid[0][0] == 1){
    19. return -1;
    20. }
    21. if (R == 1 && C == 1){
    22. return 1;
    23. }
    24. //准备工作
    25. boolean[][]vis = new boolean[R][C];
    26. int[][]path = new int[R][C];
    27. Queue<Integer> queue = new LinkedList<>();
    28. queue.add(0);
    29. vis[0][0]=true;
    30. path[0][0]=1;
    31. int r,c;
    32. while (!queue.isEmpty()){
    33. Integer pos = queue.poll();
    34. //一维数组转换为二维数组的行和列
    35. r = pos/C; // 行
    36. c = pos%C; // 列
    37. for (int d = 0; d < DIR.length; ++d) {
    38. int nr = r + DIR[d][0];
    39. int nc = c + DIR[d][1];
    40. if(inArea(nr,nc,grid) && !vis[nr][nc] && grid[nr][nc]!=1)
    41. {
    42. //记录步长
    43. path[nr][nc] = path[r][c]+1;
    44. //状态改变
    45. vis[nr][nc]=true;
    46. //此处再转换为一维数组
    47. queue.add(nc+nr*C);
    48. //状态压缩 ---> (x,y) 转移为 格子序号
    49. if(nr==R-1 && nc == C-1)
    50. {
    51. //说明到达终点
    52. return path[nr][nc];
    53. }
    54. }
    55. }
    56. }
    57. return -1;
    58. }
    59. public boolean inArea(int r,int c,int[][] grid)
    60. {
    61. return r>=0&& r<grid.length && c>=0&& c<grid[0].length;
    62. }
    63. }