A grid of 1 (land) and 0 (water) is given. An island is a group of 1s connected horizontally or vertically. Count the islands.
Input
- Line 1:
rows cols (1 ≤ rows, cols ≤ 300)
- Next
rows lines: a string of cols characters, each 0 or 1
Output
The number of islands.
Hint
Walk the grid; every time you step on unvisited land, flood-fill it (DFS or BFS) and add one to the count. Sinking each cell as you visit it is the trick that keeps it O(rows × cols).
Read from standard input and write to standard output. 5 test cases in total (3 hidden). Tests for this language run inside your browser.