Number of Islands

Medium

You are given a 2-D matrix surface of size n*m. Each cell of the surface is either 1 (land) or 0 (water).
Find the number of islands on the surface.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. Assume all four edges of the surface are all surrounded by water.

Example:
surface: [
 [1, 1, 0, 1]
 [1, 0, 1, 1]
 [0, 1, 0, 1]
]
Num islands: 3

Testing

Input Format

The first line contains an integer ‘T’ denoting the number of test cases.

For each test case the input has the following lines:

  • Two space-separated integers 'n' and 'm' denoting the number of rows and columns of the matrix.
  • n lines, each containing m space-separated integers denoting the elements of the matrix.
Output Format

For each test case, the output has a line containing the number of islands.

Sample Input

3
3 4
1 1 0 1
1 0 1 1
0 1 0 1
2 2
1 1
1 1
2 2
0 0
0 0

Expected Output

3
1
0

Constraints

1 <= T <= 10
1 <= n, m <= 200
0 <= surfaceij <= 1

Editorial Link: Editorial