|
34 | 34 |
|
35 | 35 | <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/95903878-725b-4ed9-bded-bc4aae0792a9.jpg"/> </div><br>
|
36 | 36 |
|
37 |
| -广度优先搜索一层一层地进行遍历,每层遍历都以上一层遍历的结果作为起点,遍历一个距离能访问到的所有节点。需要注意的是,遍历过的节点不能再次被遍历。 |
| 37 | +广度优先搜索一层一层地进行遍历,每层遍历都是以上一层遍历的结果作为起点,遍历一个距离能访问到的所有节点。需要注意的是,遍历过的节点不能再次被遍历。 |
38 | 38 |
|
39 | 39 | 第一层:
|
40 | 40 |
|
|
75 | 75 | 题目描述:0 表示可以经过某个位置,求解从左上角到右下角的最短路径长度。
|
76 | 76 |
|
77 | 77 | ```java
|
78 |
| -public int shortestPathBinaryMatrix(int[][] grids) { |
79 |
| - int[][] direction = {{1, -1}, {1, 0}, {1, 1}, {0, -1}, {0, 1}, {-1, -1}, {-1, 0}, {-1, 1}}; |
80 |
| - int m = grids.length, n = grids[0].length; |
81 |
| - Queue<Pair<Integer, Integer>> queue = new LinkedList<>(); |
82 |
| - queue.add(new Pair<>(0, 0)); |
83 |
| - int pathLength = 0; |
84 |
| - while (!queue.isEmpty()) { |
85 |
| - int size = queue.size(); |
86 |
| - pathLength++; |
87 |
| - while (size-- > 0) { |
88 |
| - Pair<Integer, Integer> cur = queue.poll(); |
89 |
| - int cr = cur.getKey(), cc = cur.getValue(); |
90 |
| - grids[cr][cc] = 1; // 标记 |
91 |
| - for (int[] d : direction) { |
92 |
| - int nr = cr + d[0], nc = cc + d[1]; |
93 |
| - if (nr < 0 || nr >= m || nc < 0 || nc >= n || grids[nr][nc] == 1) { |
| 78 | + public int shortestPathBinaryMatrix(int[][] grids) { |
| 79 | + if (grids == null || grids.length == 0 || grids[0].length == 0) { |
| 80 | + return -1; |
| 81 | + } |
| 82 | + int[][] direction = {{1, -1}, {1, 0}, {1, 1}, {0, -1}, {0, 1}, {-1, -1}, {-1, 0}, {-1, 1}}; |
| 83 | + int m = grids.length, n = grids[0].length; |
| 84 | + Queue<Pair<Integer, Integer>> queue = new LinkedList<>(); |
| 85 | + queue.add(new Pair<>(0, 0)); |
| 86 | + int pathLength = 0; |
| 87 | + while (!queue.isEmpty()) { |
| 88 | + int size = queue.size(); |
| 89 | + pathLength++; |
| 90 | + while (size-- > 0) { |
| 91 | + Pair<Integer, Integer> cur = queue.poll(); |
| 92 | + int cr = cur.getKey(), cc = cur.getValue(); |
| 93 | + if (grids[cr][cc] == 1) { |
94 | 94 | continue;
|
95 | 95 | }
|
96 |
| - if (nr == m - 1 && nc == n - 1) { |
97 |
| - return pathLength + 1; |
| 96 | + if (cr == m - 1 && cc == n - 1) { |
| 97 | + return pathLength; |
| 98 | + } |
| 99 | + grids[cr][cc] = 1; // 标记 |
| 100 | + for (int[] d : direction) { |
| 101 | + int nr = cr + d[0], nc = cc + d[1]; |
| 102 | + if (nr < 0 || nr >= m || nc < 0 || nc >= n) { |
| 103 | + continue; |
| 104 | + } |
| 105 | + queue.add(new Pair<>(nr, nc)); |
98 | 106 | }
|
99 |
| - queue.add(new Pair<>(nr, nc)); |
100 | 107 | }
|
101 | 108 | }
|
| 109 | + return -1; |
102 | 110 | }
|
103 |
| - return -1; |
104 |
| -} |
105 | 111 | ```
|
106 | 112 |
|
107 | 113 | ## 2. 组成整数的最小平方数数量
|
|
0 commit comments