Java 算法:求解二进制矩阵中的最短畅通路径
思路:BFS
从起点 (0,0) 出发,进行 BFS 遍历,找到最短的路径。
需要注意的是,本题是一个八连通的问题,即一个点可以向周围八个方向移动。因此,我们需要使用一个方向数组,表示八个方向,方便代码实现。
另外,我们需要使用一个 visited 数组来记录已经访问过的节点,避免重复访问。
代码如下:
import java.util.ArrayDeque;
import java.util.Queue;
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 n = grid.length;
int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}};
Queue<int[]> queue = new ArrayDeque<>();
boolean[][] visited = new boolean[n][n];
queue.offer(new int[]{0, 0});
visited[0][0] = true;
int step = 1;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int[] cur = queue.poll();
if (cur[0] == n - 1 && cur[1] == n - 1) {
return step;
}
for (int[] direction : directions) {
int nextRow = cur[0] + direction[0];
int nextCol = cur[1] + direction[1];
if (nextRow >= 0 && nextRow < n && nextCol >= 0 && nextCol < n && grid[nextRow][nextCol] == 0 && !visited[nextRow][nextCol]) {
queue.offer(new int[]{nextRow, nextCol});
visited[nextRow][nextCol] = true;
}
}
}
step++;
}
return -1;
}
}
原文地址: https://www.cveoy.top/t/topic/ot87 著作权归作者所有。请勿转载和采集!