← All coding problems
Number of Islands
mediumGraphs+20 XPTime limit 2s
A grid has land (1) and water (0). An island is a group of land cells connected up, down, left or right. Count the islands.
Input:
- line 1:
r c(rows, columns) - next
rlines: a string ofccharacters, each0or1
Output: the number of islands.
Constraints: 1 ≤ r, c ≤ 500. Large grids can be one big island — an iterative DFS/BFS avoids deep recursion.
Sample input 1
4 5 11110 11010 11000 00000
Sample output 1
1
Sample input 2
4 5 11000 11000 00100 00011
Sample output 2
3
📖 Stuck? Learn the pattern
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).