Loading content...
You are given an n × n grid of binary values where each cell contains either a 0 (representing an open/passable cell) or a 1 (representing a blocked/impassable cell). Your objective is to determine the minimum number of cells you must traverse to travel from the top-left corner (cell at position (0, 0)) to the bottom-right corner (cell at position (n-1, n-1)).
A valid path must satisfy the following conditions:
If no valid path exists from the top-left to the bottom-right corner (for example, if either the start or end cell is blocked, or if blocked cells completely obstruct all possible routes), return -1.
Movement Directions Explained: From any cell (row, col), you can move to the following 8 adjacent cells if they are within bounds and contain a 0:
grid = [[0,1],[1,0]]2The only path from (0,0) to (1,1) is a diagonal move. The path visits 2 cells: the start (0,0) and the destination (1,1). Despite the blocked cells at (0,1) and (1,0), we can traverse diagonally since diagonal movement is allowed.
grid = [[0,0,0],[1,1,0],[1,1,0]]4One valid minimum path is: (0,0) → (0,1) → (0,2) → (1,2) → (2,2). This path visits 4 cells. Moving right along the top row, then down along the right column avoids all blocked cells.
grid = [[1,0,0],[1,1,0],[1,1,0]]-1The starting cell (0,0) contains a 1 (blocked), so it is impossible to begin any path. Therefore, no valid path exists, and we return -1.
Constraints