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 of the grid are at most .
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
grid = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","1"], ["0","0","0","1","1"] ]
2
There are two distinct connected components of '1's in the grid.