← All Problems⏱ 0:00
p-4003
Number of Islands
You are given an m x n binary grid where 1 means land and 0 means water. Count how many connected islands exist. Cells connect only up, down, left, and right.
Input Format
Line 1: m n Next m lines: each line is a binary string of length n
Output Format
Print one integer: the number of islands.
Constraints
- 1 <= m, n <= 120
- grid[i][j] is 0 or 1
Examples
Input
4 5 11110 11010 11000 00000
Output
1
Explanation
All land cells connect to form one island.
Input
4 5 11000 11000 00100 00011
Output
3
Explanation
There are three disconnected components of land.
Hints
Hint 1
Hint 2
Code
>
Input
Expected Output
1
All land cells connect to form one island.
Run uses the currently selected testcase. Submit always evaluates your code against the full hidden test suite from the database.