Java 二进制矩阵最短畅通路径算法:广度优先搜索解法

问题描述:

给定一个 n x n 的二进制矩阵 grid,返回矩阵中最短畅通路径的长度。如果不存在这样的路径,返回 -1。

二进制矩阵中的畅通路径是一条从左上角单元格(即,(0, 0))到右下角单元格(即,(n - 1, n - 1))的路径,该路径同时满足下述要求:

  1. 路径途经的所有单元格的值都是 0 。
  2. 路径中所有相邻的单元格应当在 8 个方向之一上连通(即,相邻两单元之间彼此不同且共享一条边或者一个角)。

畅通路径的长度是该路径途经的单元格总数。

解题思路:

本题可以使用广度优先搜索(BFS)来解决。从起点开始,遍历所有可达的点,直到到达终点或者无法继续遍历。对于每个点,我们需要记录它的坐标和到起点的距离。使用一个队列来存储待遍历的点,每次从队列中取出一个点进行遍历,遍历结束后将可达的点加入队列中。为了避免重复遍历同一个点,我们需要使用一个 visited 数组来记录每个点是否已经被遍历过。如果到达终点,直接返回到终点的距离即可。

具体实现:

首先判断起点和终点是否为 0,如果不是,直接返回 -1,因为不可能有从起点到终点的路径。然后定义一个队列和一个 visited 数组,将起点加入队列,并将 visited 数组中起点的位置标记为已遍历。然后开始循环遍历队列,对于队列中的每个点,遍历它周围的 8 个点,如果该点未被遍历过且值为 0,则将该点加入队列,并标记为已遍历。如果该点为终点,则返回到终点的距离。如果队列为空,说明无法到达终点,返回 -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 n = grid.length;
        Queue<int[]> queue = new LinkedList<>();
        boolean[][] visited = new boolean[n][n];
        queue.offer(new int[]{0, 0});
        visited[0][0] = true;
        int[][] directions = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
        int distance = 1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                int[] current = queue.poll();
                if (current[0] == n - 1 && current[1] == n - 1) {
                    return distance;
                }
                for (int[] direction : directions) {
                    int row = current[0] + direction[0];
                    int col = current[1] + direction[1];
                    if (row >= 0 && row < n && col >= 0 && col < n && grid[row][col] == 0 && !visited[row][col]) {
                        queue.offer(new int[]{row, col});
                        visited[row][col] = true;
                    }
                }
            }
            distance++;
        }
        return -1;
    }
}
Java 二进制矩阵最短畅通路径算法:广度优先搜索解法

原文地址: https://www.cveoy.top/t/topic/ot9K 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录