Count connected land components in a grid
LinkedInSoftware Engineer · OnsiteLast updated
This question evaluates understanding of grid traversal and graph connectivity concepts, focusing on modeling a 2D matrix as adjacency relationships within the coding and algorithms domain.
You are given a 2D grid of characters where:
'1'represents land'0'represents water
A group of land cells forms an island if they are connected 4-directionally (up, down, left, right). Determine the number of islands in the grid.
Input
grid: anm x nmatrix of characters ('0'or'1').
Output
- Return an integer: the number of islands.
Constraints
1 <= m, n <= 300grid[i][j] ∈ {'0','1'}
Notes
- Diagonal adjacency does not connect islands.
- You may modify the grid in-place if desired.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.