KatInterview

Axis-Aligned Bounding Boxes of Grid Regions

Trees & GraphsAuto-graded · 24 test cases
MediumAuto-gradedTrees & Graphsbfsdfsconnected-components

Last 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 is 0 or 1. 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 <= 500
  • 0 <= cols <= 500 (per row)
  • Every cell value is 0 or 1.
  • 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.