Given a 2D grid where 0 represents a free cell and 1 represents a blocked cell, compute all cells a robot can reach starting from position (start_row, start_col).
The robot can move in four directions: up, down, left and right. It cannot move through blocked cells or outside the grid boundaries.
Return the total number of reachable cells, including the starting cell. The starting cell is guaranteed to be a free cell (0).
Function Signature
def reachable_cells(grid: list[list[int]], start_row: int, start_col: int) -> int:
Constraints
-
1 <= len(grid), len(grid[0]) <= 300
-
grid[i][j]
is
0
or
1
-
0 <= start_row < len(grid)
-
0 <= start_col < len(grid[0])
-
grid[start_row][start_col] == 0
Examples
Input: grid = [[0,0,1,0],[0,1,0,0],[0,0,0,1],[1,0,0,0]], start_row = 0, start_col = 0
Output: 12
All 12 free cells are reachable. From (0, 0) the robot can step right to (0, 1) or go down the left column to (2, 0), then along row 2 to (2, 2). From (2, 2) it goes up to (1, 2), then to (1, 3) and (0, 3), and down to (3, 2), whose neighbors (3, 1) and (3, 3) are free as well.
Input: grid = [[0,1,0],[1,0,1],[0,1,0]], start_row = 1, start_col = 1
Output: 1
The starting cell is blocked on all four sides, so the robot can only reach the starting cell itself.
Input: grid = [[0,0,1,0],[0,1,0,0],[1,0,0,0]], start_row = 0, start_col = 0
Output: 3
The blocked cells (0, 2), (1, 1) and (2, 0) form a diagonal wall. The robot reaches (0, 1) and (1, 0), but it cannot move diagonally, so the other six free cells are out of reach.