Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Number of Islands

Easy
0/40
8 upvotes
Asked in companies
DunzoTata Consultancy Services (TCS)Directi

Problem statement

You have been given a non-empty grid consisting of only 0s and 1s. You have to find the number of islands in the given grid.

An island is a group of 1s (representing land) connected horizontally, vertically or diagonally. You can assume that all four edges of the grid are surrounded by 0s (representing water).

Detailed explanation ( Input/output format, Notes, Images )
Constraints:
1 <= T <= 10
1 <= N <= 100
1 <= M <= 100
0 <= grid[i][j] <= 1

Time limit: 1 sec
Sample Input 1:
2
4 5
0 0 1 1 0
1 0 1 1 0
0 1 0 0 0 
0 0 0 0 1
1 3
1 1 1
Sample output 1:
2
1
Explanation of Sample output 1:
For the first test case, there are two islands in the grid.

For the second test case, there is only one island in the grid.
Sample Input 2:
2
1 5
0 0 0 0 0
4 4
1 0 1 0
0 1 0 1
1 0 1 0
0 1 0 1
Sample output 2:
0
1
Full screen
Console