1. 程式人生 > 其它 >1091. 二進位制矩陣中的最短路徑

1091. 二進位制矩陣中的最短路徑

給你一個 n x n 的二進位制矩陣 grid 中,返回矩陣中最短 暢通路徑 的長度。如果不存在這樣的路徑,返回 -1 。

二進位制矩陣中的 暢通路徑 是一條從 左上角 單元格(即,(0, 0))到 右下角 單元格(即,(n - 1, n - 1))的路徑,該路徑同時滿足下述要求:

路徑途經的所有單元格都的值都是 0 。
路徑中所有相鄰的單元格應當在 8 個方向之一 上連通(即,相鄰兩單元之間彼此不同且共享一條邊或者一個角)。
暢通路徑的長度 是該路徑途經的單元格總數。

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/shortest-path-in-binary-matrix


著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

import java.util.LinkedList;
import java.util.Queue;

class Solution {

    private int[] dx = {-1, -1, 0, 1, 1, 1, 0, -1};

    private int[] dy = {0, 1, 1, 1, 0, -1, -1, -1};

    public int shortestPathBinaryMatrix(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) {
            return 0;
        }

        int n = grid.length;
        int m = grid[0].length;

        if (grid[0][0] == 1 || grid[n - 1][m - 1] == 1) {
            return -1;
        }

        Queue<Info> queue = new LinkedList<>();
        queue.offer(new Info(0, 0, 1));
        grid[0][0] = 1;
        while (!queue.isEmpty()) {
            Info node = queue.poll();
            if (node.x == n - 1 && node.y == m - 1) {
                return node.step;
            }
            for (int i = 0; i < 8; ++i) {
                int nx = dx[i] + node.x;
                int ny = dy[i] + node.y;
                if (nx >= 0 && nx < n && ny >= 0 && ny < m && grid[nx][ny] == 0) {
                    queue.offer(new Info(nx, ny, node.step + 1));
                    grid[nx][ny] = 1;
                }
            }
        }
        return -1;
    }
}

class Info {
    int x;
    int y;
    int step;

    public Info(int x, int y, int step) {
        this.x = x;
        this.y = y;
        this.step = step;
    }
}
心之所向,素履以往 生如逆旅,一葦以航