Neural Mastery
← Practice
Number of Islands in 2D Gridmedium

Number of Islands in 2D Grid

medium Coding Interview Patterns 15–20 min

NumPy allowed · plain Python earns 10 bonus points

Interactive
Graph & Tree Traversal, Step by Step
Structure
Algorithm
ABCDE
visiting A -> visited order so far: [A]
queue now: [B, C]
Step 1 / 5
Both modes run the real algorithm from the linked practice problem, one step at a time -- edit the graph or pick different tree nodes and every step recomputes live.

Count disconnected land masses in a 2D matrix using connected component search.

Related Skills

Task

Implement num_islands_grid(grid): scan the matrix. Upon encountering unvisited land "1", increment island count and trigger BFS/DFS to mark all connected land cells.

Function Signature

num_islands_grid(grid: list[list[str]]) -> int

Examples

Example 1: Single L-shaped Island
Input: grid = [['1', '1', '1', '1', '0'], ['1', '1', '0', '1', '0'], ['1', '1', '0', '0', '0'], ['0', '0', '0', '0', '0']]
Output: 1
Example 2: Three Distinct Islands
Input: grid = [['1', '1', '0', '0', '0'], ['1', '1', '0', '0', '0'], ['0', '0', '1', '0', '0'], ['0', '0', '0', '1', '1']]
Output: 3

Constraints

  • 1 <= len(grid), len(grid[0]) <= 300
  • grid[r][c] is "0" or "1".
Python3Saved ✓
def num_islands_grid(grid: list[list[str]]) -> int:
"""grid: m x n binary grid where '1' is land and '0' is water.
An island is surrounded by water and formed by connecting adjacent lands horizontally or vertically.
Return total number of islands."""
# Your implementation here
pass

Case 1: Single L-shaped Island
Input: grid = [['1', '1', '1', '1', '0'], ['1', '1', '0', '1', '0'], ['1', '1', '0', '0', '0'], ['0', '0', '0', '0', '0']]
Expected: 1
Case 2: Three Distinct Islands
Input: grid = [['1', '1', '0', '0', '0'], ['1', '1', '0', '0', '0'], ['0', '0', '1', '0', '0'], ['0', '0', '0', '1', '1']]
Expected: 3