Count islands in a binary grid
Problem
You are given an m x n grid of characters where each cell is either '1' (representing land) or '0' (representing water). An island is formed by connecting adjacent land cells horizontally or vertically (not diagonally). The grid edges are considered to be surrounded by water.
Your task is to return the total number of islands in the grid.
Input
grid: A 2D array (list of lists) of characters, where each character is either'0'or'1'.
Output
- An integer representing the count of distinct islands.
Constraints
1 <= m, n <= 300grid[i][j]will always be either'0'or'1'.
Example
Input:
[
['1','1','0','0','0'],
['1','1','0','0','0'],
['0','0','1','0','0'],
['0','0','0','1','1']
]
Output:
3
Explanation: There are three distinct, disconnected land masses.
AI interview prep
Core dilemma
Efficiently identifying and counting all disconnected components (islands) in a 2D grid while ensuring complete traversal and avoiding redundant processing, especially under potential memory or recursion depth constraints for large grids.
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 islands in a binary grid
Problem
You are given an m x n grid of characters where each cell is either '1' (representing land) or '0' (representing water). An island is formed by connecting adjacent land cells horizontally or vertically (not diagonally). The grid edges are considered to be surrounded by water.
Your task is to return the total number of islands in the grid.
Input
grid: A 2D array (list of lists) of characters, where each character is either'0'or'1'.
Output
- An integer representing the count of distinct islands.
Constraints
1 <= m, n <= 300grid[i][j]will always be either'0'or'1'.
Example
Input:
[
['1','1','0','0','0'],
['1','1','0','0','0'],
['0','0','1','0','0'],
['0','0','0','1','1']
]
Output:
3
Explanation: There are three distinct, disconnected land masses.