Java 实现二进制矩阵最短畅通路径算法
思路:BFS
由于要求最短路径,可以使用 BFS 来解决。从左上角出发,每次遍历相邻的 8 个方向,如果该方向上的格子可以通行且未被访问过,则加入队列中,并标记为已访问。每次遍历时,记录下当前遍历的层数,即路径长度,直到到达右下角或者队列为空为止。
代码如下:
public 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 n = grid.length;
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{0, 0});
boolean[][] visited = new boolean[n][n];
visited[0][0] = true;
int pathLength = 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 == n - 1 && col == n - 1) {
return pathLength;
}
for (int[] direction : directions) {
int nextRow = row + direction[0];
int nextCol = col + 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;
}
}
}
pathLength++;
}
return -1;
}
}
原文地址: https://www.cveoy.top/t/topic/ot8L 著作权归作者所有。请勿转载和采集!