⌘K
Flycodx

Number of Islands

Number of Islands

MediumGraphs50% accepted

Given an m×n 2D binary grid where '1' represents land and '0' represents water, count the number of islands. An island is a group of '1's connected horizontally or vertically, surrounded by water on all sides. Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer. Example: 4×5 grid → 1 island or 3 islands based on connectivity

Input format — only if your code reads from stdin

Input format (stdin): - First line: two integers m (rows) and n (cols) - Next m lines: each containing n integers (0 or 1) separated by spaces Output: a single integer — the number of islands.

Approach

Iterate every cell. When you find a '1', increment the island count and run DFS/BFS to mark all cells in this island as '0' (or visited). This way each island is counted exactly once when its first '1' is encountered.

Input

4 5 1 1 1 1 0 1 1 0 1 0 1 1 0 0 0 0 0 0 0 0

Output

1
  • •1 ≤ m, n ≤ 300, grid[i][j] is '0' or '1'
solution.py
Loading editor...
Test 1
Test 2
Test 3

Press Run to test your custom input, or Submit to judge against all test cases.

Sign in to continue

Create a free account to run code, submit solutions and track progress.

  • Free forever — no credit card
  • 10+ languages with live execution
  • Points, streaks & leaderboards
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3