Java 代码实现:二进制矩阵中最短畅通路径
Java 代码实现:二进制矩阵中最短畅通路径
给定一个 n x n 的二进制矩阵 grid,返回矩阵中最短畅通路径的长度。如果不存在这样的路径,返回 -1。
二进制矩阵中的畅通路径是一条从左上角单元格(即,(0, 0))到右下角单元格(即,(n - 1, n - 1))的路径,该路径同时满足下述要求:
- 路径途经的所有单元格的值都是 0。
- 路径中所有相邻的单元格应当在 8 个方向之一上连通(即,相邻两单元之间彼此不同且共享一条边或者一个角)。
- 畅通路径的长度是该路径途经的单元格总数。
解题思路:
本题可以使用 BFS(广度优先搜索)来解决。从起点开始,将其加入队列中,然后一层一层地遍历周围的点,直到找到终点为止。在遍历过程中,需要注意一些细节:
- 遍历过的点需要标记,避免重复遍历。
- 遍历过程中需要记录每个点到起点的距离,用于计算最短路径长度。
- 遍历过程中需要判断当前点是否为终点,如果是,则直接返回最短路径长度。
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 n = grid.length;
int[][] directions = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{0, 0, 1}); // 起点 (0, 0) 距离为 1
boolean[][] visited = new boolean[n][n];
visited[0][0] = true;
while (!queue.isEmpty()) {
int[] current = queue.poll();
int row = current[0];
int col = current[1];
int distance = current[2];
if (row == n - 1 && col == n - 1) {
return distance;
}
for (int[] dir : directions) {
int nextRow = row + dir[0];
int nextCol = col + dir[1];
if (nextRow >= 0 && nextRow < n && nextCol >= 0 && nextCol < n && grid[nextRow][nextCol] == 0 && !visited[nextRow][nextCol]) {
visited[nextRow][nextCol] = true;
queue.offer(new int[]{nextRow, nextCol, distance + 1});
}
}
}
return -1; // 没有找到畅通路径
}
}
原文地址: https://www.cveoy.top/t/topic/fW9M 著作权归作者所有。请勿转载和采集!