Java 二进制矩阵最短畅通路径算法
Java 二进制矩阵最短畅通路径算法
这道题可以使用广度优先搜索(BFS)来解决。具体思路如下:
- 定义一个变量 step 来记录路径的长度,初始值为 1。
- 定义一个队列 queue 来保存待搜索的节点,将起点 (0, 0) 加入队列。
- 对于队列中的每个节点,搜索其相邻的节点,如果相邻节点的值为 0,且未被访问过,则将其加入队列,并将相邻节点的值设为 1,表示已经访问过。
- 每次搜索完一个节点,将 step 加 1,表示路径长度加 1。
- 如果队列为空,表示无法到达终点,返回 -1。否则,继续搜索直到找到终点为止。
Java 代码如下:
class Solution {
public int shortestPathBinaryMatrix(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0 || grid[0][0] == 1 || grid[grid.length - 1][grid[0].length - 1] == 1) {
return -1;
}
int[][] directions = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
int step = 1;
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{0, 0});
grid[0][0] = 1;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int[] current = queue.poll();
int row = current[0];
int col = current[1];
if (row == grid.length - 1 && col == grid[0].length - 1) {
return step;
}
for (int[] direction : directions) {
int nextRow = row + direction[0];
int nextCol = col + direction[1];
if (nextRow >= 0 && nextRow < grid.length && nextCol >= 0 && nextCol < grid[0].length && grid[nextRow][nextCol] == 0) {
queue.offer(new int[]{nextRow, nextCol});
grid[nextRow][nextCol] = 1;
}
}
}
step++;
}
return -1;
}
}
示例:
Input: grid = [[0,1],[1,0]]
Output: 2
解释:
从 (0, 0) 到 (1, 1) 的最短路径长度为 2。
原文地址: https://www.cveoy.top/t/topic/ot8G 著作权归作者所有。请勿转载和采集!