#C8357. Counting Islands in a Grid
Counting Islands in a Grid
Counting Islands in a Grid
You are given one or more 2D grids of integers representing a map, where each cell in the grid is either 1
(land) or 0
(water). Your task is to count the number of islands in each grid. An island is a group of horizontally or vertically (but not diagonally) adjacent lands.
The input consists of multiple test cases. For each test case, the first line contains two integers n and m (the number of rows and columns respectively). This is followed by n lines, each containing m space separated integers (either 0 or 1). The input terminates when a test case with n = 0
and m = 0
is encountered.
Note: In any formulas, use LaTeX format. For example, if you refer to the grid size, you may denote it as $n \times m$.
inputFormat
The input is given via standard input and consists of multiple test cases. Each test case begins with a line containing two integers n and m ($n \times m$ grid), followed by n lines with m integers each (either 0 or 1). The input terminates with a line containing 0 0
.
outputFormat
For each test case, output a single integer on a new line representing the number of islands found in the grid.
## sample6 5
1 1 0 0 0
1 1 0 0 1
0 0 0 1 1
0 0 0 0 0
1 0 0 1 1
1 1 0 1 1
4 4
1 1 1 1
1 1 1 1
0 0 0 0
0 0 0 0
0 0
4
1
</p>