Count Connected Land Regions
Company: eBay
Role: Software Engineer
Category: Coding & Algorithms
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of graph connectivity and grid traversal, specifically the detection of connected components within a 2D matrix. It is commonly asked to assess algorithmic problem-solving, efficiency and handling of matrix-based data structures; it belongs to the Coding & Algorithms domain and tests practical implementation skills alongside conceptual understanding of graph-related complexity under the given input constraints.
Constraints
- 1 <= m, n <= 300
- grid[i][j] is either '0' or '1'
Examples
Input: ([['1','1','0','0','0'],['1','1','0','0','0'],['0','0','1','0','0'],['0','0','0','1','1']],)
Expected Output: 3
Explanation: There are three separate groups of connected land cells.
Input: ([['0']],)
Expected Output: 0
Explanation: A single water cell contains no land regions.
Input: ([['1']],)
Expected Output: 1
Explanation: A single land cell forms one region by itself.
Input: ([['1','0','1'],['0','1','0'],['1','0','1']],)
Expected Output: 5
Explanation: Diagonal connections do not count, so each land cell is its own region.
Input: ([['1','1','1'],['0','1','0'],['1','1','1']],)
Expected Output: 1
Explanation: All land cells are connected through horizontal and vertical paths, forming one region.
Input: ([['1','0','1','1','0','1']],)
Expected Output: 3
Explanation: The row contains three separate land groups: ['1'], ['1','1'], and ['1'].
Hints
- Treat each land cell as a node in a graph, where edges exist only in the four cardinal directions.
- Whenever you find an unvisited land cell, run BFS or DFS from it to mark the entire region before continuing.