Bad Grass
InterviewTime limit1sMemory limit128 MB
Count connected components of nonzero cells in a grid, where two cells connect if they touch horizontally, vertically, or diagonally.
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 rows and columns of 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: and .
Input
The first line contains two space-separated integers and .
Each of the next lines describes one row of the map with space-separated integers; the -th of these lines is row .
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.