KatInterview

Flood Fill with Step Budget on an 8-Connected Grid

Trees & GraphsAuto-graded · 22 test cases
MediumAuto-gradedTrees & Graphsbfsgridgraph-traversal

Last 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 <= 500
  • 0 <= 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.