Count Islands in a Grid
Count Islands in a Grid
Given an m x n binary grid, where 1 represents land and 0 represents water, determine the total number of islands.
An island is defined as a group of connected land cells. Two land cells are considered connected if they are adjacent horizontally or vertically. Diagonal adjacency does not constitute a connection.
Implementation Details
Implement a function with the following signature (example in Python):
def count_islands(grid: list[list[int]]) -> int:
pass
Constraints and Requirements
- The input grid may be empty (i.e.,
morncould be zero). - You are permitted to mutate the input grid in place to mark visited cells, provided this choice is clearly documented. Alternatively, you may use a separate data structure to track visited cells.
- You must also provide a set of test cases designed to identify common implementation errors, particularly those related to incorrectly handling diagonal connections.
AI interview prep
Core dilemma
Efficiently identifying and counting distinct connected components (islands) in a 2D grid while strictly adhering to connectivity rules and avoiding redundant processing.
2 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 Grid
Count Islands in a Grid
Given an m x n binary grid, where 1 represents land and 0 represents water, determine the total number of islands.
An island is defined as a group of connected land cells. Two land cells are considered connected if they are adjacent horizontally or vertically. Diagonal adjacency does not constitute a connection.
Implementation Details
Implement a function with the following signature (example in Python):
def count_islands(grid: list[list[int]]) -> int:
pass
Constraints and Requirements
- The input grid may be empty (i.e.,
morncould be zero). - You are permitted to mutate the input grid in place to mark visited cells, provided this choice is clearly documented. Alternatively, you may use a separate data structure to track visited cells.
- You must also provide a set of test cases designed to identify common implementation errors, particularly those related to incorrectly handling diagonal connections.