LeetCode

Post by ailswan Aug. 31, 2024

1091. Shortest Path in Binary Matrix

Problem Statement

link: LeetCode.cn LeetCode Given an n x n binary matrix grid, return the length of the shortest clear path in the matrix. If there is no clear path, return -1.

A clear path in a binary matrix is a path from the top-left cell (i.e., (0, 0)) to the bottom-right cell (i.e., (n - 1, n - 1)) such that:

All the visited cells of the path are 0. All the adjacent cells of the path are 8-directionally connected (i.e., they are different and they share an edge or a corner). The length of a clear path is the number of visited cells of this path.

Example:

Input: grid = [[0,1],[1,0]] Output: 2

Input: grid = [[0,0,0],[1,1,0],[1,1,0]] Output: 4

Input: grid = [[1,0,0],[1,1,0],[1,1,0]] Output: -1

Constraints: n == grid.length n == grid[i].length 1 <= n <= 100 grid[i][j] is 0 or 1

Solution Approach

The solution uses BFS to explore the matrix from the top-left to the bottom-right cell, updating distances and checking valid moves to find the shortest clear path. If the end cell is reached, the path length is returned; otherwise, -1 is returned if no path exists.

Algorithm

  1. Breadth-First Search (BFS) Approach: The algorithm uses BFS to explore the matrix level-by-level, ensuring that the shortest path is found if it exists.
  2. 8-Directional Movement: The BFS explores all 8 possible directions (horizontal, vertical, and diagonal) from each cell to find the shortest path to the bottom-right corner.
  3. Matrix Update and Queue Management: The matrix cells are updated to mark them as visited, and a queue is used to manage the BFS traversal, with each cell’s distance from the start being tracked.

Complexity

time complexity: O(n^2) space complexity: O(n^2)

Implement

    class Solution:
    def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int:
        if grid[0][0]:
            return -1
        n = len(grid)
        grid[0][0] == 1
        q = deque([(0,0)])
        ans = 1
        while q:
            for _ in range(len(q)):
                i, j = q.popleft()
                if i == j == n - 1:
                    return ans
                for x in range(i - 1, i + 2): # -1 。 0 。 +1
                    for y in range(j - 1, j + 2):# -1, 0. + 1
                        if 0 <= x < n and 0 <= y < n and grid[x][y] == 0:
                            grid[x][y] = 1
                            q.append((x, y))
            ans += 1
        return -1