← 返回 bytedance 的题目列表Classic Island Problem on Grid (BFS/DFS)
类型:online_judge
Given a 2D grid grid consisting of 0/1, where 1 represents land and 0 represents water.
Compute the number of islands in the grid.
An island is defined as a connected component of lands (1) connected via 4-directional adjacency (up, down, left, right). Cells outside the grid are water.
Input
The first line contains two integers m n (rows and columns).
The next m lines describe the grid (either as a string of length n or n space-separated digits).
Output
Print one integer: the number of islands.
Constraints
1 <= m, n <= 2000 (typical interview scale; avoid recursion depth issues; iterative BFS/DFS recommended)
4-directional adjacency only
Example
Input grid:
11000
11000
00100
00011 Output: 3
Example
Input
4 5
11000
11000
00100
00011
Output
3