Number of Islands
Time limit1sMemory limit128 MB
Given a grid of land and sea cells with 8-directional adjacency, count the connected land components.
Problem
You are given a map of land and sea made up of square cells. Write a program that counts the number of islands.
From any cell you may walk to a cell that is adjacent horizontally, vertically, or diagonally. In other words, each cell is connected to up to 8 neighboring cells.
Two land cells belong to the same island if there is a path that walks from one to the other while stepping only on land cells. The map is surrounded by sea, and you cannot move outside the map.
Input
The input consists of several test cases. The first line of each test case contains the width and the height of the map. and are positive integers not greater than .
The next lines describe the map, each line containing integers separated by spaces. denotes land and denotes sea.
The last line of the input contains two zeros; this line is not processed.
Output
For each test case, print the number of islands, one per line.