
Let ‘MATRIX1’ be :
1 1
0 0
Let ‘MATRIX2’ be:
1 1
0 0
All the 1s present in ‘MATRIX2’ can be considered a good island. There is 1 good island present.
The first line of input contains an integer ‘T’, denoting the number of test cases.
The first line of each test case contains two space-separated integers, ‘M’ and ‘N’, representing the size of the matrices.
The next ‘M’ lines of each test case contain ‘N’ space-separated integers, representing the cells of ‘MATRIX1’.
The next ‘M’ lines of each test case contain ‘N’ space-separated integers, representing the cells of ‘MATRIX2’.
For each test case, print the number of good islands.
Print output of each test case in a separate line.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= M, N <= 10^3
0 <= MATRIX1[i][j], MATRIX2[i][j] <= 1
Time Limit: 1 sec
The basic idea is to find the ‘1’ present in ‘MATRIX2’ which is not visited yet and then recursively traverse all the cells present on that island while checking for the ‘1s’ present in the ‘MATRIX1’ at the same position or not. If all the cells of an island in ‘MATRIX2’ are present in the ‘MATRIX1’, we count it as a good island. We also change the value of visited cells to ‘-1’ so we don’t traverse them again.
DFS(‘M’, ‘N’, ‘MATRIX1’, ‘MATRIX2’, ‘i’, ‘j’, ‘GOOD’) (where ‘M’ and ‘N’ are the size of the matrices, ‘MATRIX1’ and ‘MATRIX2’ are the given matrices, ‘i’ and ‘j’ are starting position, and ‘GOOD’ is for checking the validity of good island).
The basic idea is to find the 1s in the ‘MATRIX2’ which are not visited yet and then check whether the same position consists of 1s or not in the ‘MATRIX1’. We use bfs traversal to find the number of good islands. Initially, we insert 1s present in the ‘MATRIX2’ in a queue and then keep on traveling in 4 different directions while checking for the 1s in the ‘MATRIX1’. If all the cells of an island in ‘MATRIX2’ are present in the ‘MATRIX1’, we count it as a good island. We also change the value of visited cells to ‘-1’ so we don’t traverse them again.