Flood Fill with Step Budget on an 8-Connected Grid
Trees & GraphsAuto-graded · 22 test casesLast updated
Tests BFS-based grid traversal by counting distinct empty cells reachable from a starting position within a fixed number of 8-directional moves.
Problem
A warehouse floor is modeled as an M x N grid of integers. Each cell holds either 0 (open floor) or 1 (a shelving unit that blocks movement). An autonomous cart starts at a given open cell and may take at most k moves total. On each move the cart can step to any of the eight neighboring cells — the four cardinal directions plus the four diagonals. The cart cannot enter a cell containing a shelving unit.
Return the number of distinct open cells the cart can occupy, including its starting cell.
Two cells are distinct if they differ in row, column, or both. The cart does not need to use all k moves; a cell counts as long as it is reachable within the budget.
Constraints
1 <= M, N <= 5000 <= k <= 10^5- The starting cell is always open (
grid[start_r][start_c] == 0). - Diagonal movement is not blocked by adjacent orthogonal obstacles — the cart only needs the destination cell itself to be open.
Examples
Example 1
Input: count_reachable_cells([[0, 0, 0], [0, 1, 0], [0, 0, 0]], [0, 0], 1)
Output: 3
Example 2
Input: count_reachable_cells([[0, 0], [0, 0]], [0, 0], 2)
Output: 4
Hints
Hint 1
Think about what graph algorithm naturally finds the shortest number of steps to every reachable cell from a single source — and why that matters here.
Hint 2
Mark a cell as visited the moment you add it to the frontier, not when you process it. What goes wrong if you wait until you pop it?
Hint 3
You never need to expand a cell that was reached exactly at step k, because any neighbor would require k + 1 steps. Build that pruning directly into your loop.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Why BFS?
A cell is reachable within k moves if and only if the shortest path from the start to that cell uses at most k steps. Because every move costs exactly one step, BFS explores cells in non-decreasing order of distance from the source — the first time BFS reaches a cell is along a shortest path. That property makes BFS the natural fit; DFS does not guarantee shortest paths and would require tracking and potentially re-visiting cells, making the logic significantly more complicated.
Algorithm
- Seed the BFS queue with the starting cell at distance 0, mark it visited, and initialize the count to 1.
- Pop the front of the queue. If its stored distance equals
k, skip expansion — any neighbor would be at distancek + 1, which is over budget. - Otherwise, try all eight neighbor offsets (the full
{-1, 0, 1}²grid minus(0, 0)). Enqueue a neighbor only when all three of these hold:- It lies within the grid boundaries.
- Its cell value is
0(open floor). - It has not been visited yet.
- Mark a cell visited and increment the count at the moment of enqueuing, not at the moment of popping. Waiting until pop allows the same cell to enter the queue multiple times from different neighbors at the same distance, which inflates the count and wastes work.
- Return the final count once the queue is empty.
Why it is correct
- BFS guarantees that the distance stored with each cell when it is first enqueued is its true minimum step count from the start.
- The pruning at
dist == kis safe: any cell truly reachable withinksteps has a predecessor reachable withink − 1steps, and that predecessor will be expanded before it is pruned. - The visited array ensures each cell is counted exactly once, so there is no double-counting.
- Obstacle cells are never enqueued, so no path crosses through them.
Edge cases
k = 0: the start cell is popped immediately withdist == 0 == k, so nothing expands. The answer is 1.- Start surrounded by obstacles or walls on all sides: the answer is 1.
1 x 1grid: the answer is 1.klarger than the number of cells: the budget never binds; the answer is the size of the 8-connected open component containing the start.
Complexity
- Time:
O(M · N). Each cell is enqueued and dequeued at most once; each dequeue checks at most 8 neighbors. The step budgetkdoes not appear in this bound — BFS stops naturally when the queue drains. - Space:
O(M · N)for the visited matrix and the BFS queue.
Full solution
from collections import deque
from typing import List, Tuple
def count_reachable_cells(grid: List[List[int]], start: Tuple[int, int], k: int) -> int:
m, n = len(grid), len(grid[0])
sr, sc = start
visited = [[False] * n for _ in range(m)]
visited[sr][sc] = True
queue = deque([(sr, sc, 0)])
count = 1
directions = [(-1, -1), (-1, 0), (-1, 1),
(0, -1), (0, 1),
(1, -1), (1, 0), (1, 1)]
while queue:
r, c, dist = queue.popleft()
if dist == k:
continue
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < m and 0 <= nc < n and grid[nr][nc] == 0 and not visited[nr][nc]:
visited[nr][nc] = True
count += 1
queue.append((nr, nc, dist + 1))
return count