v9.1.1
Menu

Count Connected Regions

mediumFREEUnion-FindUnion-Find, Connected ComponentsCV - DSA

Problem Statement

In image segmentation, connected component labeling is essential for identifying distinct objects. Union-Find (Disjoint Set Union) is an efficient data structure for this task.

Given a 2D binary grid where 1 represents foreground pixels and 0 represents background, count the number of connected foreground regions using Union-Find.

Two pixels are connected if they are adjacent horizontally or vertically (4-connectivity).

Applications

  • Object counting in binary images
  • Blob detection
  • Particle analysis in microscopy

Constraints

  • 1≤rows,cols≤1001 \leq rows, cols \leq 100
  • Grid contains only 0s and 1s

Example

Input
grid = [[1, 1, 0], [0, 1, 0], [1, 0, 1]]
Output
3
Reasoning
  • Input: grid is a 3×33 \times 3 binary image. A 1 is a foreground pixel and a 0 is background, so the foreground pixels sit at (row, column) positions (0,0)(0,0), (0,1)(0,1), (1,1)(1,1), (2,0)(2,0) and (2,2)(2,2).
  • Connectivity: two foreground pixels belong together when they share an edge, i.e. their positions differ by exactly 1 in the row or in the column, never both. Connection is transitive: if AA touches BB and BB touches CC, all three form one region.
  • (0,0)(0,0) touches (0,1)(0,1) horizontally, and (0,1)(0,1) touches (1,1)(1,1) vertically, so these three pixels form one L-shaped region.
  • (2,0)(2,0) has background above it at (1,0)(1,0) and to its right at (2,1)(2,1), so it is a region on its own. The same holds for (2,2)(2,2), which has 0s at (1,2)(1,2) and (2,1)(2,1).
  • Output: 1+1+1=1 + 1 + 1 = 3 regions, an integer count of regions rather than of pixels.
  • Notice that (2,0)(2,0) and (2,2)(2,2) both touch (1,1)(1,1) diagonally. Under 8-connectivity the whole grid would be a single region; 4-connectivity is what splits it into three.

Learn this in

More from CV - DSA

solution.py

Test results

Sign in to run your code against the test cases.