PIXELBANKv9.1.0
Menu

Connected Components in Binary Image (Islands)

In image segmentation and feature extraction, counting distinct foreground objects requires identifying connected components.

You are given a 2D binary grid (matrix) where '1' represents land (foreground pixel) and '0' represents water (background pixel). An "island" is defined as a maximal group of connected '1's, connected horizontally or vertically (4-directionally).

Your task is to find the total number of disjoint islands (connected components) present in the grid. You must modify the grid in place to keep track of visited land pixels (e.g., by changing '1's to a placeholder value) to ensure each component is counted exactly once.

Constraints:

  • The grid contains only '1's (land) and '0's (water).
  • The dimensions M×NM \times N of the grid are at most 50×5050 \times 50.

About Topic: This problem directly implements the core logic required for connectivity analysis in pipelines like the Canny Edge Detector, which use BFS or DFS to link local responses into coherent features or edges. This technique is a fundamental step in converting raw pixel data into discrete objects for further classification or analysis.

Example:

Input:
grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","1"],
  ["0","0","0","1","1"]
]
Output:
2
Reasoning:

There are two distinct connected components of '1's in the grid.

🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Connected Components in Binary Image (Islands) - Medium | PixelBank