Given a Matrix consisting of 0s and 1s. Find the number of islands of connected 1s present in the matrix. - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Sunday 12 July 2020

Given a Matrix consisting of 0s and 1s. Find the number of islands of connected 1s present in the matrix.

Given a Matrix consisting of 0s and 1s. Find the number of islands of connected 1s present in the matrix.
Given a Matrix consisting of 0s and 1s. Find the number of islands of connected 1s present in the matrix. 

Given a Matrix consisting of 0s and 1s. Find the number of islands of connected 1s present in the matrix. 
Note: A 1 is said to be connected if it has another 1 around it (either of the 8 directions).


You don't need to read input or print anything. Your task is to complete the function findIslands() which takes the matrix A and its dimensions N and M as inputs and returns the number of islands of connected 1s present in the matrix. A 1 is said to be connected if it has another 1 around it (either of the 8 directions).


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

Output
2
2

Explanation:
Testcase 1: The graph will look like
1 1 0
0 0 1
1
Here, two islands will be formed
First island will be formed by elements {A[0][0] ,  A[0][1], A[1][2], A[2][2]}
Second island will be formed by {A[2][0]}.
Testcase 2: 
The graph will look like
1 1 0 0
0 0 1 0
0 0 0 1
1 0 0
Here, two islands will be formed
First island will be formed by elements {A[0][0] ,  A[0][1], A[1][2], A[2][3]}
Second island will be formed by {A[3][1]}.


// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;

int findIslands(vector<int> A[], int N, int M);

int main() {

    int T;
    cin >> T;
    while (T--) {
        int N, M;
        cin >> N >> M;
        vector<int> A[N];
        for (int i = 0; i < N; i++) {
            vector<int> temp(M);
            A[i] = temp;
            for (int j = 0; j < M; j++) {
                cin >> A[i][j];
            }
        }
        cout << findIslands(A, N, M) << endl;
    }
    return 0;
}// } Driver Code Ends


/*you are required to complete this method*/

/*  Function to find the number of islands in the given graph
*   A[]: input array
*   N, M: Row and column of a given matrix
*/
void test(vector<int> a[],int i,int j,int n,int m)
{
    if(i<0||j<0||i>n||j>m||a[i][j]!=1)
    return;
    a[i][j]=2;
    test(a,i,j+1,n,m);
    test(a,i,j-1,n,m);
    test(a,i-1,j,n,m);
    test(a,i+1,j,n,m);
    test(a,i-1,j-1,n,m);
    test(a,i+1,j+1,n,m);
    test(a,i-1,j+1,n,m);
    test(a,i+1,j-1,n,m);
}
int findIslands(vector<int> A[], int N, int M) {

    // Your code here
    int island=0;
    for(int i=0;i<N;++i)
    {
        for(int j=0;j<M;++j)
        {
            if(A[i][j]==1)
            {
                test(A,i,j,N,M);
                island++;
            }
        }
    }
    
    return island;

}