Count 1s in binary matrix having remaining indices of its row and column filled with 0s

Given a binary matrix, mat[][] of size M * N, the task is to count the number of 1s from the given binary matrix whose corresponding row and column consists of 0s only in the remaining indices.
Examples:Â
Input: mat[][] = {{1, 0, 0}, {0, 0, 1}, {0, 0, 0}}Â
Output: 2Â
Explanation:Â
The only two cells satisfying the conditions are (0, 0) and (1, 2).Â
Therefore, the count is 2.ÂInput: mat[][] = {{1, 0}, {1, 1}}Â
Output: 0Â
Naive Approach: The simplest approach is to iterate over the matrix and check the given condition for all 1s present in the given matrix by traversing its corresponding row and column. Increase count of all 1s satisfying the condition. Finally, print the count as the required answer.
Time Complexity: O(M*N2)Â
Auxiliary Space: O(M + N)
Efficient Approach: The above approach can be optimized based on the idea that the sum of such rows and columns will be only 1. Follow the steps below to solve the problem:Â
- Initialize two arrays, rows[] and cols[], to store the sum of each row and each column of the matrix respectively.
- Initialize a variable, say cnt, to store the count of 1s satisfying given condition.
- Traverse the matrix for every mat[i][j] = 1, check if rows[i] and cols[j] is 1.If found to be true, then increment cnt.
- After completing the above steps, print the final value of count.
Below is the implementation of the above approach:
C++
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to count required 1s// from the given matrixint numSpecial(vector<vector<int> >& mat){Â
    // Stores the dimensions of the mat[][]    int m = mat.size(), n = mat[0].size();Â
    int rows[m];    int cols[n];Â
    int i, j;Â
    // Calculate sum of rows    for (i = 0; i < m; i++) {        rows[i] = 0;        for (j = 0; j < n; j++)            rows[i] += mat[i][j];    }Â
    // Calculate sum of columns    for (i = 0; i < n; i++) {Â
        cols[i] = 0;        for (j = 0; j < m; j++)            cols[i] += mat[j][i];    }Â
    // Stores required count of 1s    int cnt = 0;    for (i = 0; i < m; i++) {        for (j = 0; j < n; j++) {Â
            // If current cell is 1            // and sum of row and column is 1            if (mat[i][j] == 1 && rows[i] == 1                && cols[j] == 1)Â
                // Increment count of 1s                cnt++;        }    }Â
    // Return the final count    return cnt;}Â
// Driver Codeint main(){    // Given matrix    vector<vector<int> > mat        = { { 1, 0, 0 }, { 0, 0, 1 }, { 0, 0, 0 } };Â
    // Function Call    cout << numSpecial(mat) << endl;Â
    return 0;} |
Java
// Java program for the above approachclass GFG{     // Function to count required 1s// from the given matrixstatic int numSpecial(int [][]mat){         // Stores the dimensions of the mat[][]    int m = mat.length;    int n = mat[0].length;      int []rows = new int[m];    int []cols = new int[n];      int i, j;      // Calculate sum of rows    for(i = 0; i < m; i++)    {        rows[i] = 0;                 for(j = 0; j < n; j++)            rows[i] += mat[i][j];    }      // Calculate sum of columns    for(i = 0; i < n; i++)    {        cols[i] = 0;                 for(j = 0; j < m; j++)            cols[i] += mat[j][i];    }      // Stores required count of 1s    int cnt = 0;         for(i = 0; i < m; i++)     {        for(j = 0; j < n; j++)        {                         // If current cell is 1            // and sum of row and column is 1            if (mat[i][j] == 1 &&                   rows[i] == 1 &&                   cols[j] == 1)                  // Increment count of 1s                cnt++;        }    }         // Return the final count    return cnt;}  // Driver Codepublic static void main(String[] args){         // Given matrix    int [][]mat = { { 1, 0, 0 },                    { 0, 0, 1 },                     { 0, 0, 0 } };      // Function call    System.out.print(numSpecial(mat) + "\n");}}  // This code is contributed by Amit Katiyar |
Python3
# Python3 program for the above approachÂ
# Function to count required 1s# from the given matrixdef numSpecial(mat):         # Stores the dimensions     # of the mat    m = len(mat)    n = len(mat[0])Â
    rows = [0] * m    cols = [0] * nÂ
    i, j = 0, 0Â
    # Calculate sum of rows    for i in range(m):        rows[i] = 0Â
        for j in range(n):            rows[i] += mat[i][j]Â
    # Calculate sum of columns    for i in range(n):        cols[i] = 0Â
        for j in range(m):            cols[i] += mat[j][i]Â
    # Stores required count of 1s    cnt = 0Â
    for i in range(m):        for j in range(n):Â
            # If current cell is 1            # and sum of row and column is 1            if (mat[i][j] == 1 and                  rows[i] == 1 and                  cols[j] == 1):Â
                # Increment count of 1s                cnt += 1Â
    # Return the final count    return cntÂ
# Driver Codeif __name__ == '__main__':         # Given matrix    mat = [ [ 1, 0, 0 ],             [ 0, 0, 1 ],            [ 0, 0, 0 ] ]Â
    # Function call    print(numSpecial(mat))Â
# This code is contributed by Amit Katiyar |
C#
// C# program for the above approachusing System;Â
class GFG{     // Function to count required 1s// from the given matrixstatic int numSpecial(int [,]mat){         // Stores the dimensions of the [,]mat    int m = mat.GetLength(0);    int n = mat.GetLength(1);      int []rows = new int[m];    int []cols = new int[n];      int i, j;      // Calculate sum of rows    for(i = 0; i < m; i++)    {        rows[i] = 0;                 for(j = 0; j < n; j++)            rows[i] += mat[i, j];    }      // Calculate sum of columns    for(i = 0; i < n; i++)    {        cols[i] = 0;                 for(j = 0; j < m; j++)            cols[i] += mat[j, i];    }      // Stores required count of 1s    int cnt = 0;         for(i = 0; i < m; i++)     {        for(j = 0; j < n; j++)        {                         // If current cell is 1 and             // sum of row and column is 1            if (mat[i, j] == 1 &&                   rows[i] == 1 &&                   cols[j] == 1)                  // Increment count of 1s                cnt++;        }    }         // Return the readonly count    return cnt;}  // Driver Codepublic static void Main(String[] args){         // Given matrix    int [,]mat = { { 1, 0, 0 },                   { 0, 0, 1 },                    { 0, 0, 0 } };      // Function call    Console.Write(numSpecial(mat) + "\n");}}  // This code is contributed by Amit Katiyar |
Javascript
<script>// javascript program for the above approachÂ
// Function to count required 1s// from the given matrixfunction numSpecial(mat){         // Stores the dimensions of the mat    var m = mat.length;    var n = mat[0].length;      var rows = Array.from({length: m}, (_, i) => 0);    var cols = Array.from({length: n}, (_, i) => 0);    var i, j;      // Calculate sum of rows    for(i = 0; i < m; i++)    {        rows[i] = 0;                 for(j = 0; j < n; j++)            rows[i] += mat[i][j];    }      // Calculate sum of columns    for(i = 0; i < n; i++)    {        cols[i] = 0;                 for(j = 0; j < m; j++)            cols[i] += mat[j][i];    }      // Stores required count of 1s    var cnt = 0;     for(i = 0; i < m; i++)     {        for(j = 0; j < n; j++)        {                         // If current cell is 1            // and sum of row and column is 1            if (mat[i][j] == 1 &&                   rows[i] == 1 &&                   cols[j] == 1)                  // Increment count of 1s                cnt++;        }    }         // Return the final count    return cnt;}  // Driver CodeÂ
// Given matrix    var mat = [ [ 1, 0, 0 ],                    [ 0, 0, 1 ],                     [ 0, 0, 0 ] ];  // Function calldocument.write(numSpecial(mat) + "\n");Â
// This code is contributed by Amit Katiyar </script> |
2
Â
Time Complexity: O(N*M), as we are using nested loops to traverse N*M times.
Auxiliary Space: O(N+M), as we are using extra space for two arrays row and col.
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



