grid filling
rectangular regions
grid partitioning
computational geometry
discrete mathematics

minimum number of rectangular regions to fill a grid

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

This problem is easy in one special case and much harder in the general case. If the entire grid must be filled and there are no obstacles, the minimum number of rectangles is obviously 1: use the whole grid as one rectangle. The interesting version is when only certain cells must be covered, and you want the fewest axis-aligned rectangles whose union matches that target set exactly.

Clarify the Problem Variant First

There are two common interpretations:

  1. Cover the entire m x n grid.
  2. Cover only the marked cells in a grid of 0 and 1 values.

For the first interpretation, the answer is trivial:

text
minimum rectangles = 1

For the second interpretation, the problem becomes a rectangle-cover optimization problem. That is the version most people actually mean when they ask about a minimum number of rectangular regions.

A Small Example

Suppose 1 means "must be covered" and 0 means "leave empty":

text
11 1 1 0
21 1 1 0
30 0 1 1
40 0 1 1

This can be covered exactly with two rectangles:

  • one rectangle over the top-left 2 x 3 block
  • one rectangle over the bottom-right 2 x 2 block

That is clearly better than covering each row or each individual cell.

Why the General Problem Is Hard

Once arbitrary holes or disconnected patterns appear, finding the minimum exact rectangle cover is combinatorial. A greedy choice that looks good locally can force extra rectangles later.

For example, in this grid:

text
1 1 1
1 0 1
1 1 1

The largest rectangle strategy fails immediately because the central hole prevents one big rectangle, and several competing covers exist. Choosing a wide rectangle first may block a smaller optimal decomposition later.

That is why exact solutions usually use backtracking, branch and bound, or dynamic programming for small grids, while large grids often rely on heuristics.

A Backtracking Approach for Small Grids

One practical exact strategy is:

  1. Find the first uncovered 1 cell.
  2. Enumerate every rectangle starting at that cell that contains only 1 cells and uncovered cells.
  3. Mark that rectangle as covered.
  4. Recurse and keep the best solution found so far.

Here is a small Python implementation for exact search on modest grid sizes:

python
1from math import inf
2
3grid = [
4    [1, 1, 1, 0],
5    [1, 1, 1, 0],
6    [0, 0, 1, 1],
7    [0, 0, 1, 1],
8]
9
10rows = len(grid)
11cols = len(grid[0])
12covered = [[False] * cols for _ in range(rows)]
13best = inf
14
15
16def first_uncovered():
17    for r in range(rows):
18        for c in range(cols):
19            if grid[r][c] == 1 and not covered[r][c]:
20                return r, c
21    return None
22
23
24def valid_rectangle(r1, c1, r2, c2):
25    for r in range(r1, r2 + 1):
26        for c in range(c1, c2 + 1):
27            if grid[r][c] != 1 or covered[r][c]:
28                return False
29    return True
30
31
32def fill_rectangle(r1, c1, r2, c2, value):
33    for r in range(r1, r2 + 1):
34        for c in range(c1, c2 + 1):
35            covered[r][c] = value
36
37
38def search(count):
39    global best
40    if count >= best:
41        return
42
43    start = first_uncovered()
44    if start is None:
45        best = count
46        return
47
48    r1, c1 = start
49
50    for r2 in range(r1, rows):
51        for c2 in range(c1, cols):
52            if valid_rectangle(r1, c1, r2, c2):
53                fill_rectangle(r1, c1, r2, c2, True)
54                search(count + 1)
55                fill_rectangle(r1, c1, r2, c2, False)
56
57
58search(0)
59print(best)

For the sample grid, this prints 2.

Why This Works

The algorithm is correct because every exact cover can be viewed as a choice of one rectangle covering the first uncovered required cell, followed by an exact cover of the remaining cells. By exploring all such choices and keeping the smallest count, the search eventually finds the optimum.

The downside is runtime. The number of candidate rectangle combinations grows quickly, so this approach is best for small instances or interview-style exercises.

Heuristics for Larger Instances

If the grid is large, exact search may be too slow. Common heuristics include:

  • repeatedly taking the largest valid rectangle
  • merging adjacent rows with identical runs of 1 cells
  • decomposing connected components first
  • using integer programming or SAT-based formulations for exact offline solving

These methods trade guaranteed optimality for speed or solver convenience.

Common Pitfalls

One common mistake is forgetting to define whether overlapping is allowed. Most exact-cover variants do not allow overlap when the goal is to represent a shape exactly.

Another issue is assuming the largest rectangle first is always optimal. It often works well, but it is not guaranteed to produce the minimum number of rectangles.

Developers also sometimes confuse the trivial full-grid case with the harder marked-cell case. If every cell must be covered and there are no constraints, the answer is just 1.

Finally, if you implement backtracking, prune aggressively. Without pruning by current best count, the search becomes much slower than necessary.

Summary

  • If the whole rectangular grid must be filled, the minimum number of rectangles is 1.
  • The interesting variant is covering a selected set of marked cells exactly.
  • That general problem is combinatorial, so greedy methods are not always optimal.
  • Exact solutions for small grids can be built with backtracking and pruning.
  • Large instances often need heuristics or solver-based optimization approaches.

Course illustration
Course illustration

All Rights Reserved.