Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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:
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:

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: 

  1. Initialize two arrays, rows[] and cols[], to store the sum of each row and each column of the matrix respectively.
  2. Initialize a variable, say cnt, to store the count of 1s satisfying given condition.
  3. 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.
  4. 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 matrix
int 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 Code
int 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 approach
class GFG{
     
// Function to count required 1s
// from the given matrix
static 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 Code
public 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 matrix
def 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 Code
if __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 approach
using System;
 
class GFG{
     
// Function to count required 1s
// from the given matrix
static 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 Code
public 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 matrix
function 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 call
document.write(numSpecial(mat) + "\n");
 
// This code is contributed by Amit Katiyar
</script>


Output: 

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.
 



Last Updated : 31 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads