Bad Grass

Interview

Time limit1sMemory limit128 MB

Summary
Count connected components of nonzero cells in a grid, where two cells connect if they touch horizontally, vertically, or diagonally.
Level

Easy3 of 10

Topics
Graph, DFS, BFS, Matrix
Solved
No attempts yet

Problem

Bessie is grazing in the pasture. She only enjoys the tender, delicious grass that grows on the wide flats at the farm's base elevation (elevation 0). Grass just 1 meter higher is tough and unappetizing, and it gets worse as the elevation increases.

This bad grass grows on the sides of hills, forming a set of 'islands' amid the sea of tender, delicious grass. Bessie wants to count how many islands of bad grass her pasture contains.

She divides the pasture into a grid of RR rows and CC columns of 1m×1m1\text{m} \times 1\text{m} squares and measures each square's elevation above the base level, rounding it to a non-negative integer. Every square of tasty grass has elevation 0.

Two squares belong to the same island if they are adjacent horizontally, vertically, or diagonally. Count how many islands are formed by the squares whose elevation is not 0 (the bad grass).

Constraints: 1<R≤10001 < R \le 1000 and 1<C≤10001 < C \le 1000.

Input

The first line contains two space-separated integers RR and CC.

Each of the next RR lines describes one row of the map with CC space-separated integers; the ii-th of these lines is row ii.

Output

Print a single integer: the number of islands.

Hint

In the sample there are two islands: a large one that fills much of the left region and extends all the way to the bottom through diagonal adjacency, and a small one in the upper-right corner.

Examples1

  1. Example 1

    Input
    8 7
    4 3 2 2 1 0 1
    3 3 3 2 1 0 1
    2 2 2 2 1 0 0
    2 1 1 1 1 0 0
    1 1 0 0 0 1 0
    0 0 0 1 1 1 0
    0 1 2 2 1 1 0
    0 1 1 1 2 1 0
    
    Expected output
    2