Number of Islands (Connected Components in a Grid)

VERY HARD · C · 5000ms

Zooming out to a satellite map of connected campus buildings (marked as a grid of land/water), Rakib needs to count how many separate "islands" of connected buildings exist. Given an N×M grid of '1' (land) and '0' (water), count the number of islands, where an island is a maximal group of '1's connected 4-directionally (not diagonally).

Input

Line1: N M. Next N lines: grid rows of '0'/'1'.

Output

Number of islands.

Constraints

1 ≤ N,M ≤ 500

Sample Input

4 5
11000
11000
00100
00011

Sample Output

3
main.c
Loading editor…

Write C, then Run (custom I/O) or Submit (sample tests). ⌘/Ctrl+Enter submits.

Number of Islands (Connected Components in a Grid) · DIU ContestHub