Axis-Aligned Bounding Boxes of Grid Regions
Trees & GraphsAuto-graded · 24 test casesLast updated
Tests BFS/DFS connected-components traversal on a 2D grid to locate distinct filled regions and compute the tightest enclosing rectangle for each.
Axis-Aligned Bounding Boxes of Grid Regions
You are given a 2D grid of integers. Each cell holds either 0 (vacant) or 1 (occupied). Two occupied cells belong to the same region when they share an edge — that is, they are directly adjacent horizontally or vertically. Diagonal contact does not count.
For every distinct region, compute its bounding box: the smallest axis-aligned rectangle that contains every cell in the region. Represent a bounding box as [top_row, left_col, bottom_row, right_col], where (top_row, left_col) is the upper-left corner and (bottom_row, right_col) is the lower-right corner, using 0-based indices.
Return the list of all bounding boxes. The boxes may appear in any order.
Input
grid: a 2D list of integers, where every value is0or1. Rows may differ in length (jagged grid). The grid may be empty.
Output
A list of 4-element lists [top_row, left_col, bottom_row, right_col], one per region. Return an empty list if there are no occupied cells.
Constraints
0 <= rows <= 5000 <= cols <= 500(per row)- Every cell value is
0or1. - Rows are not guaranteed to have the same length.
- Required time complexity:
O(rows × cols). - A bounding box may contain vacant cells or even cells belonging to other regions (e.g. when a region wraps around another).
Examples
Example 1
Input: find_region_bounding_boxes([[1, 1, 0], [1, 0, 0], [0, 0, 1]])
Output: [[0, 0, 1, 1], [2, 2, 2, 2]]
Example 2
Input: find_region_bounding_boxes([[0, 0], [0, 0]])
Output: []
Example 3
Input: find_region_bounding_boxes([[1, 1, 1], [1, 1, 1]])
Output: [[0, 0, 1, 2]]
Example 4
Input: find_region_bounding_boxes([[1, 0, 1], [0], [1, 1]])
Output: [[0, 0, 0, 0], [0, 2, 0, 2], [2, 0, 2, 1]]
Hints
Hint 1
Scan every cell left-to-right, top-to-bottom. The first time you encounter an unvisited occupied cell, you have found a new region — launch a flood-fill from there.
Hint 2
Use an explicit stack or queue instead of recursion. A 500×500 grid that is entirely occupied forms one region of 250 000 cells, which will overflow Python's default recursion limit.
Hint 3
During the flood-fill, maintain four running values — the minimum and maximum row and the minimum and maximum column seen so far. When the fill ends those four values are exactly the bounding box.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a classic connected-components problem on a 2D grid with 4-directional adjacency.
Core idea
Scan every cell in row-major order. Whenever an occupied, unvisited cell is found, it is the entry point of a previously unseen region. Launch an iterative flood-fill (DFS with an explicit stack) from that cell. While the fill runs, track four values — min_r, max_r, min_c, max_c — updating them for every cell visited. When the fill finishes, those four values define the tightest axis-aligned rectangle enclosing the region.
Why iterative and not recursive?
A 500×500 grid that is entirely occupied forms a single region of 250 000 cells. Recursive DFS would produce a call stack of that depth and crash with a RecursionError in Python (default limit ~1 000). An explicit stack on the heap has no such constraint.
Why mark cells visited on push, not on pop?
If a cell is marked only when it is popped, two different neighbors can both push the same cell before either processes it. That leads to redundant work and, in the worst case, exponential blowup. Marking on push ensures each cell enters the stack exactly once.
Why is the bounding box exact?
The fill visits every cell reachable from the starting cell through 4-connected 1 cells, and nothing else. The running min/max over those cells therefore produces the tightest possible axis-aligned rectangle. Note that the rectangle may enclose vacant cells or cells from other regions (e.g. a U-shaped region); that is expected behavior.
Correctness on jagged grids
Rather than assuming all rows share the same length, the neighbor check uses len(grid[nr]) for the column bound of row nr. The visited array is also built per-row. This handles grids where rows have different lengths.
Edge cases
- Empty grid or no occupied cells: the outer loops do nothing and
[]is returned. - Entire grid occupied: one region, one box
[0, 0, rows-1, cols-1]. This is the case that breaks recursive DFS. - Single-cell region: box degenerates to
[r, c, r, c]. - Single row or column: the min/max logic handles it without special-casing.
Complexity
- Time:
O(rows × cols). The outer scan visits each cell once. Each occupied cell is pushed and popped from the stack once, and its four neighbors are inspected a constant number of times. - Space:
O(rows × cols)for thevisitedstructure. In the worst case the stack also holdsO(rows × cols)entries (all-ones grid). The output list holds at mostO(rows × cols / 2)boxes (checkerboard pattern).
Reference solution
from typing import List
def find_region_bounding_boxes(grid: List[List[int]]) -> List[List[int]]:
rows = len(grid)
# Use bytearray for a compact, fast visited structure that handles jagged rows.
visited = [bytearray(len(row)) for row in grid]
boxes = []
for r in range(rows):
for c, cell in enumerate(grid[r]):
if cell != 1 or visited[r][c]:
continue
# First unvisited occupied cell of a new region: iterative DFS.
visited[r][c] = 1
stack = [(r, c)]
min_r = max_r = r
min_c = max_c = c
while stack:
cr, cc = stack.pop()
# Expand the bounding box to include this cell.
if cr < min_r: min_r = cr
if cr > max_r: max_r = cr
if cc < min_c: min_c = cc
if cc > max_c: max_c = cc
# Explore 4-directional neighbours.
for nr, nc in ((cr - 1, cc), (cr + 1, cc), (cr, cc - 1), (cr, cc + 1)):
if (0 <= nr < rows
and 0 <= nc < len(grid[nr])
and grid[nr][nc] == 1
and not visited[nr][nc]):
visited[nr][nc] = 1 # mark on push to avoid duplicate pushes
stack.append((nr, nc))
boxes.append([min_r, min_c, max_r, max_c])
return boxes