解题思路:

本题可以使用广度优先搜索(BFS)来解决。从起点开始,每次只考虑当前位置的八个方向,如果该方向的位置在矩阵内,且该位置为 0 且未被访问过,则可以继续往该方向前进,并将该位置标记为已访问过。直到找到终点位置(即右下角的位置)或者搜索完所有可能的路径。

需要注意的是,每次前进的距离为1,因此需要在每个位置上记录到起点的距离,即该位置的'步数'。具体来说,可以创建一个二维数组来记录每个位置到起点的距离,初始化为 -1(表示该位置未被访问过),起点位置的距离为 0,每次前进一步,距离加 1。在每个位置上更新距离值时,需要同时将该位置标记为已访问过。

当搜索到终点位置时,返回该位置的距离值即可。如果搜索完所有可能的路径后仍然没有到达终点位置,则说明不存在畅通路径,返回 -1。

时间复杂度:O(n^2),其中 n 是矩阵的边长。每个位置最多被遍历一次,因此总时间复杂度为 O(n^2)。

Java 代码:

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 n = grid.length;
        int[][] distance = new int[n][n];
        for (int i = 0; i < n; i++) {
            Arrays.fill(distance[i], -1);
        }
        distance[0][0] = 1;
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{0, 0});
        int[][] directions = {{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
        while (!queue.isEmpty()) {
            int[] current = queue.poll();
            int row = current[0];
            int col = current[1];
            if (row == n - 1 && col == n - 1) {
                return distance[row][col];
            }
            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 && distance[nextRow][nextCol] == -1) {
                    distance[nextRow][nextCol] = distance[row][col] + 1;
                    queue.offer(new int[]{nextRow, nextCol});
                }
            }
        }
        return -1;
    }
}
Java 实现 寻找二进制矩阵中的最短畅通路径

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

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