Leetcode 1091: Shortest Path in Binary Matrix

grid47
grid47
Exploring patterns and algorithms
Jul 20, 2024 8 min read

Given an n x n binary matrix grid, find the shortest clear path in the matrix that connects the top-left cell (0, 0) to the bottom-right cell (n-1, n-1). A clear path is defined as a path where all cells along the path are 0, and the path can move in 8 possible directions (up, down, left, right, and diagonals). Return the length of the shortest clear path, or -1 if no such path exists.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer n representing the size of the grid, followed by an n x n binary matrix `grid`, where each cell contains either a 0 or a 1. A 0 represents a free cell and a 1 represents an obstacle. Additionally, the goal is to find the shortest clear path from the top-left cell (0, 0) to the bottom-right cell (n-1, n-1).
Example: Input: grid = [[0,1],[1,0]]
Constraints:
• 1 <= n <= 100
• grid[i][j] is either 0 or 1
Output: Return the length of the shortest clear path in the grid, or -1 if no such path exists. The path must be clear, with each cell in the path containing 0, and the cells must be connected by 8-directional movement.
Example: Output: 2
Constraints:
• If no clear path exists, return -1.
Goal: To find the shortest path, we use a breadth-first search (BFS) approach, which explores all possible paths and ensures the shortest path is found first.
Steps:
• 1. Initialize a queue with the top-left cell (0, 0) and mark it as visited.
• 2. Use BFS to explore all 8-directional neighbors of each cell.
• 3. If the bottom-right cell (n-1, n-1) is reached, return the length of the path.
• 4. If the queue is empty and the bottom-right cell is not reached, return -1.
Goal: Ensure the solution works within the given grid size and handles both small and large grid cases efficiently.
Steps:
• The grid is square (n x n), with 1 <= n <= 100.
• Each cell contains either 0 or 1, where 0 indicates an empty space and 1 indicates an obstacle.
Assumptions:
• The grid is properly formed with dimensions n x n.
• The pathfinding should consider only cells that contain 0.
Input: Input: grid = [[0,1],[1,0]]
Explanation: The grid is a 2x2 matrix. The clear path is from (0, 0) to (1, 1), and the shortest path length is 2, as we move diagonally.

Input: Input: grid = [[0,0,0],[1,1,0],[1,1,0]]
Explanation: In this case, the shortest path from (0, 0) to (2, 2) is 4, taking the clear path through (0,0) -> (0,1) -> (1,2) -> (2,2).

Input: Input: grid = [[1,0,0],[1,1,0],[1,1,0]]
Explanation: In this case, it's impossible to reach (2, 2) from (0, 0) due to obstacles, so the output is -1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus