Practice/Amazon/Leetcode 1091. Shortest Path in Binary Matrix
CodingMust
You are given an n × n square grid where each cell contains either 0 or 1. A cell with value 0 represents an open space that you can walk through, while a cell with value 1 represents a blocked obstacle that cannot be traversed.
Your task is to find the length of the shortest path from the top-left corner cell at position (0, 0) to the bottom-right corner cell at position (n-1, n-1). You can move in all 8 directions: up, down, left, right, and the four diagonal directions.
The path length is defined as the number of cells visited along the path, including both the start and end cells.
If no valid path exists from start to finish, return -1.
Example 1:
Input: grid = [[0,1],[0,0]] Output: 3 Explanation: The shortest path is (0,0) → (1,0) → (1,1), which visits 3 cells.
Example 2:
Input: grid = [[0,0,0],[1,1,0],[1,1,0]] Output: 4 Explanation: One shortest path is (0,0) → (0,1) → (1,2) → (2,2), visiting 4 cells.
Example 3:
Input: grid = [[1,0,0],[0,0,0],[0,0,0]] Output: -1 Explanation: The starting cell is blocked, so no path can exist.