VOOZH about

URL: https://www.geeksforgeeks.org/dsa/unique-cells-binary-matrix/

⇱ Unique cells in a binary matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Unique cells in a binary matrix

Last Updated : 12 Dec, 2022

Given a matrix of size n × m consisting of 0's and 1's. We need to find the number of unique cells with value 1 such that the corresponding entire row and the entire column do not have another 1. Return the number of unique cells.

Examples: 

Input : mat[][] = {0, 1, 0, 0
 0, 0, 1, 0
 1, 0, 0, 1}
Answer : 2
The two 1s that are unique
in their rows and columns
are highlighted.

Input : mat[][] = { 
{0, 0, 0, 0, 0, 0, 1}
{0, 1, 0, 0, 0, 0, 0}
{0, 0, 0, 0, 0, 1, 0}
{1, 0, 0, 0, 0, 0, 0}
{0, 0, 1, 0, 0, 0, 1}
Output : 3

Method 1- Brute Force Approach:

In this approach, we are going to check for each cell with value 1 whether the corresponding rows satisfy our requirement. We will check in the corresponding rows and columns of each cell with the value 1.

Implementation:


Output
2

Time Complexity: O((n*m)*(n+m)) 
Auxiliary Space: O(1), since no extra space has been taken.

This goes to the order of cubic due to check condition for every corresponding row and column

Method 2- O(n*m) Approach: 

In this approach, we are going to use extra space for rowsum array and colsum array and then check for each cell with value 1 whether the corresponding rowsum array and colsum array values are 1. 

Implementation:


Output
2

Time Complexity : O(n*m) 
Auxiliary Space: O(n+m)

Comment
Article Tags:
Article Tags: