VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-original-matrix-from-the-given-and-matrix/

⇱ Find the original matrix from the given AND matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the original matrix from the given AND matrix

Last Updated : 28 Feb, 2023

Given a binary matrix B[][] of size N*M, the task is to find a matrix A[][] of the same size such that B[i][j] is the bitwise AND of all the elements in ith row and jth column of A[][].

Examples:

Input: B[][] = { {1, 0, 1}, {0, 0, 0} }
Output: { {1, 1, 1}, {1, 0, 1} }
Explanation:
1 1 1  ?  1 0 1
1 0 1       0 0 0

Input: B[][] = { {0, 0}, {1, 1} }
Output: -1

Approach: Follow the below idea to solve the problem:

If any cell contains 1 means that in every cell of that row and column there should not be any 0 because if it is it will dominate 1.

Follow the steps to solve this problem:

  • Calculate the number of rows and columns of a given matrix.
    • Store the matrix in a temporary matrix say original.
  • Find out the rows and columns containing 1 and insert them into two sets (say row and col).
    • Traverse the set and then update the row and column with 1.
  • Create a variable result and store the matrix in a temporary matrix say result.
  • Clear the set row and col.
  • Find out the rows and columns containing 0 and insert them into set.
    • Traverse the set and update 0 to every row and every column.
  • Check if the changed matrix is not equal to the original matrix then print -1.
    • Else print matrix result i.e., originally the matrix A which is obtained from matrix B.

Below is the implementation of the above approach.


Output
1 1 1 
1 0 1 

Time Complexity: O(N*M)
Auxiliary Space: O(N*M)

Comment