Given a Matrix containing 0s and 1s. Find the unit area of the largest region of 1s . - Codeprg

Breaking

programing News Travel Computer Engineering Science Blogging Earning

Wednesday, 24 June 2020

Given a Matrix containing 0s and 1s. Find the unit area of the largest region of 1s .

Given a Matrix containing 0s and 1s. Find the unit area of the largest region of 1s.

Input:
2
3 3
1 1 0 0 0 1 1 0 1
1 3
1 1 1

Explanation:
Testcase 1:
 Matrix can be shown as follows:
1 1 0
0 0 1
1 0 1

The largest region of 1s in the above matrix is with a total of 4 1s (colored in Red).
Testcase 2: Matrix can be shown as follows:
1 1 1
The largest region of 1s in the above matrix is with a total of 3 1s (colored in Red).


Given a Matrix containing 0s and 1s. Find the unit area of the largest region of 1s .
Given a Matrix containing 0s and 1s. Find the unit area of the largest region of 1s .

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

// } Driver Code Ends


/*  Function to find the area of 1s
 *   SIZE: declared globally for matrix definition
 *   n, m: row and column of matrix
 *   A[][]: 2D matrix from input */
void dfs(int i, int j, int & cnt, int n, int m, int a[SIZE][SIZE]) {
    if (i < 0 || i >= n || j < 0 || j >= m || a[i][j] == 0)
        return;

    a[i][j] = 0;
    cnt++;
    dfs(i + 1, j, cnt, n, m, a);
    dfs(i - 1, j, cnt, n, m, a);
    dfs(i, j + 1, cnt, n, m, a);
    dfs(i, j - 1, cnt, n, m, a);
    dfs(i + 1, j + 1, cnt, n, m, a);
    dfs(i + 1, j - 1, cnt, n, m, a);
    dfs(i - 1, j + 1, cnt, n, m, a);
    dfs(i - 1, j - 1, cnt, n, m, a);
}

int findMaxArea(int N, int M, int A[SIZE][SIZE]) {
    // Your code here

    int p, res = 0;

    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < M; ++j) {
            if (A[i][j] == 1) {
                p = 0;
                dfs(i, j, p, N, M, A);
                res = max(p, res);
            }

        }
    }

    return res;
}

// { Driver Code Starts.

int main() {
    int t;
    cin >> t;
    while (t--) {
        int n, m;
        cin >> n >> m;

        int g[SIZE][SIZE];

        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                cin >> g[i][j];

        cout << findMaxArea(n, m, g) << endl;
    }

    return 0;
} // } Driver Code Ends