All problems

Problem 162

Number of Islands

Medium · 20 pts · Graph, Matrix, Breadth-First Search, Depth-First Search

Problem

You are given a grid of R rows and C columns, where '1' is land and '0' is water. An island is a group of land cells connected horizontally or vertically (diagonal neighbours do not count). Count the islands. Everything outside the grid is water. Scan the grid. Each time you find a land cell that has not been visited, you have found a new island: count it, then flood fill it with BFS or DFS to mark all its cells as visited.

Input

First line: integers R and C. Next R lines: C characters, each '0' or '1'.

Output

Print the number of islands.

Constraints

1 <= R, C <= 300

Example input

4 5
11000
11000
00100
00011

Example output

3

Explanation

The four 1's in the top-left corner form one island, the single 1 in the middle forms a second, and the two 1's in the bottom-right form a third. None of these groups touch horizontally or vertically, so there are 3 islands.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Connected Components Next: Shortest Path in an Unweighted Graph