Number of Islands
Number of Islands
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
Output
- •
1 ≤ m, n ≤ 300, grid[i][j] is '0' or '1'
More Graphs problems
Browse all coding problems →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