Count connected components in a binary grid
Count Connected Components in a Binary Grid
You are given an m x n grid where each cell contains either a '0' or a '1':
- A
'1'represents land. - A
'0'represents water.
Two land cells are considered connected if they share an edge (4-directional adjacency: up, down, left, or right).
Your task is to return the total number of connected land components, often referred to as "islands".
Input
grid: Anm x nmatrix of characters, wheregrid[i][j]is either'0'or'1'.
Output
- An integer representing the number of islands.
Constraints
1 <= m, n <= 300grid[i][j]is guaranteed to be either'0'or'1'.
Example
Input:
1 1 0 0
1 0 0 1
0 0 1 1
Output: 3
AI interview prep
Core dilemma
Efficiently traversing a grid to identify distinct connected components while ensuring each cell is processed exactly once to maintain optimal time complexity and avoid infinite loops.
3 tradeoffs and 3 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Count connected components in a binary grid
Count Connected Components in a Binary Grid
You are given an m x n grid where each cell contains either a '0' or a '1':
- A
'1'represents land. - A
'0'represents water.
Two land cells are considered connected if they share an edge (4-directional adjacency: up, down, left, or right).
Your task is to return the total number of connected land components, often referred to as "islands".
Input
grid: Anm x nmatrix of characters, wheregrid[i][j]is either'0'or'1'.
Output
- An integer representing the number of islands.
Constraints
1 <= m, n <= 300grid[i][j]is guaranteed to be either'0'or'1'.
Example
Input:
1 1 0 0
1 0 0 1
0 0 1 1
Output: 3