
You are given ‘grid’ = [[1,1,1 ,1 1], [1, 0, 0, 1 1],[ 1, 1, 1, 1,1], [1, 0, 1, 1, 1],[1, 1, 1, 1, 1]], Here the given grid is

We can clearly see that there are 2 islands. Hence the answer is 2.
The first line of input contains a single integer ‘T’ representing the number of test cases.
The first line of each test case contains two space-separated integers ‘N’ and ‘M’ representing the row and column of the grid.
The next ‘N’ lines of each test case contain ‘M’ space-separated integers representing the elements of the grid.
For each test case print a single integer, representing the number of islands in the grid.
Print a separate line of each test case.
1 <= T <= 10
1 <= N, M <= 10^3
grid[i][i] = 0 or 1
Time Limit: 1 sec
You do not need to print anything. It has already been taken care of. Just implement the given function.
In this approach, we see that a ‘0’ could be a part of the island only if its connect by all sides from either ‘1’ or a ‘0’, i.e if a ‘0’ is at the boundary of the grid, then all the ‘0’ connected to it will not be in an island.
Therefore we can start graph traversal from a ‘0’ and its connected component will only be valid if none of its elements lies on the border of the matrix. It is clear that we need to find all the valid connected components.
Therefore from DFS every time we find a ‘1’ we return 1 and if we reach outside the grid we return 0. Then we can multiply the results of each dfs call and check if the current component is valid or not.
We create a DFS(grid, row, col), where grid is the matrix given and row and col are the positions of the current element in the matrix.
Algorithm:
In this approach, we will do the same thing of counting all the valid components of the graph, but instead of a depth-first search, we can use the breadth-first search. This method is also called the flood fill method.
We create a bfs(grid, row, col, visited): function, where grid is the given grid, row and col are the position of the current node and visited, is the set of visited nodes.
Algorithm: