Open In App

Find the original matrix from the given AND matrix

Last Updated : 28 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

C++
// C++ code to implement the approach

#include <bits/stdc++.h>
using namespace std;

// Function to find the matrix A from B
void solve(vector<vector<bool> >& arr)
{
    int n = arr.size();
    int m = arr[0].size();

    set<int> row;
    set<int> col;

    vector<vector<bool> > original(arr);

    // first find rows and columns containing 1
    // and insert into set
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (arr[i][j]) {
                row.insert(i);
                col.insert(j);
            }
        }
    }

    // Set 1 to every row
    for (auto it : row) {
        for (int i = 0; i < m; i++) {
            arr[it][i] = 1;
        }
    }

    // Set 1 to every column
    for (auto it : col) {
        for (int i = 0; i < n; i++) {
            arr[i][it] = 1;
        }
    }

    vector<vector<bool> > result(arr);

    row.clear();
    col.clear();

    // first find rows and columns containing 0
    // and insert into set
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (!arr[i][j]) {
                row.insert(i);
                col.insert(j);
            }
        }
    }

    // Set 0 to every row
    for (auto it : row) {
        for (int i = 0; i < m; i++) {
            arr[it][i] = 0;
        }
    }

    // Set 0 to every column
    for (auto it : col) {
        for (int i = 0; i < n; i++) {
            arr[i][it] = 0;
        }
    }

    // If the modified matrix and original matrix
    // is not equal then print -1
    if (arr != original) {
        cout << -1 << endl;
    }

    // Else print the matrix res
    else {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                cout << result[i][j] << " ";
            }
            cout << endl;
        }
    }
}

// Driver Code
int main()
{

    vector<vector<bool> > v = { { 1, 0, 1 }, { 0, 0, 0 } };

    solve(v);

    return 0;
}
Java
// Java code to implement the approach
import java.io.*;
import java.util.*;

class GFG {

  static void solve(boolean[][] arr)
  {
    int n = arr.length;
    int m = arr[0].length;

    Set<Integer> row = new HashSet<>();
    Set<Integer> col = new HashSet<>();

    boolean[][] original = new boolean[n][m];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        original[i][j] = arr[i][j];
      }
    }

    // first find rows and columns containing 1
    // and insert into set
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        if (arr[i][j]) {
          row.add(i);
          col.add(j);
        }
      }
    }

    for (var it : row) {
      for (int i = 0; i < m; i++) {
        arr[it][i] = true;
      }
    }

    for (var it : col) {
      for (int i = 0; i < n; i++) {
        arr[i][it] = true;
      }
    }

    boolean[][] result = new boolean[n][m];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        result[i][j] = arr[i][j];
      }
    }

    row.clear();
    col.clear();

    // first find rows and columns containing 0
    // and insert into set
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        if (!arr[i][j]) {
          row.add(i);
          col.add(j);
        }
      }
    }

    // Set 0 to every row
    for (var it : row) {
      for (int i = 0; i < m; i++) {
        arr[it][i] = false;
      }
    }

    // Set 0 to every column
    for (var it : col) {
      for (int i = 0; i < n; i++) {
        arr[i][it] = false;
      }
    }

    // If the modified matrix and original matrix
    // is not equal then print -1
    if (arr == original) {
      System.out.println(-1);
    }

    // Else print the matrix res
    else {
      for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
          if (result[i][j]) {
            System.out.print(1 + " ");
          }
          else {
            System.out.print(0 + " ");
          }
        }
        System.out.println();
      }
    }
  }

  public static void main(String[] args)
  {
    boolean[][] v = { { true, false, true },
                     { false, false, false } };
    solve(v);
  }
}

// This code is contributed by lokeshmvs21.
Python3
# Python code to implement the approach
import copy

# Function to find the matrix A from B
def solve(arr):
    n = len(arr)
    m = len(arr[0])
    
    row = set()
    col = set()
    
    original=copy.deepcopy(arr)
    
    # first find rows and columns containing 1
    # and insert into set
    
    for i in range(n):
        for j in range(m):
            if(arr[i][j]):
                row.add(i)
                col.add(j)
                
    # Set 1 to every row
    for it in row:
        for i in range(m):
            arr[it][i] = 1
        
    # Set 1 to every column
    for it in col:
        for i in range(n):
            arr[i][it] = 1
    
    result=copy.deepcopy(arr)
    
    row.clear()
    col.clear()
    
    # first find rows and columns containing 0
    # and insert into set
    for i in range(n):
        for j in range(m):
            if(not (arr[i][j])):
                row.add(i)
                col.add(j)
    
    # Set 0 to every row
    for it in row:
        for i in range(m):
            arr[it][i] = 0
        
    # Set 0 to every column
    for it in col:
        for i in range(n):
            arr[i][it] = 0
            
    # If the modified matrix and original matrix
    # is not equal then print -1
    if(arr != original):
        print("-1")
        
    # Else print the matrix res
    else:
        for i in range(n):
            for j in range(m):
                print(result[i][j], end=" ")
            print()
    
# Driver Code
v = [[1, 0, 1],[0, 0, 0]]
solve(v)

# This code is contributed by Pushpesh Raj.
C#
// C# code to implement the approach
using System;
using System.Collections.Generic;

class GFG {
  static void solve(bool[, ] arr)
  {
    int n = arr.GetLength(0);
    int m = arr.GetLength(1);

    HashSet<int> row = new HashSet<int>();
    HashSet<int> col = new HashSet<int>();

    bool[, ] original = new bool[n, m];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        original[i, j] = arr[i, j];
      }
    }

    // first find rows and columns containing 1
    // and insert into set
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        if (arr[i, j]) {
          row.Add(i);
          col.Add(j);
        }
      }
    }

    foreach(var it in row)
    {
      for (int i = 0; i < m; i++) {
        arr[it, i] = true;
      }
    }

    foreach(var it in col)
    {
      for (int i = 0; i < n; i++) {
        arr[i, it] = true;
      }
    }

    bool[, ] result = new bool[n, m];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        result[i, j] = arr[i, j];
      }
    }

    row.Clear();
    col.Clear();

    // first find rows and columns containing 0
    // and insert into set
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        if (!arr[i, j]) {
          row.Add(i);
          col.Add(j);
        }
      }
    }

    // Set 0 to every row
    foreach(var it in row)
    {
      for (int i = 0; i < m; i++) {
        arr[it, i] = false;
      }
    }

    // Set 0 to every column
    foreach(var it in col)
    {
      for (int i = 0; i < n; i++) {
        arr[i, it] = false;
      }
    }

    // If the modified matrix and original matrix
    // is not equal then print -1
    if (arr == original) {
      Console.WriteLine(-1);
    }

    // Else print the matrix res
    else {
      for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
          if (result[i, j]) {
            Console.Write(1 + " ");
          }
          else {
            Console.Write(0 + " ");
          }
        }
        Console.WriteLine();
      }
    }
  }

  public static void Main(string[] args)
  {
    bool[, ] v
      = new bool[2, 3] { { true, false, true },
                        { false, false, false } };
    solve(v);
  }
}

// This code is contributed by Tapesh(tapeshdua420)
JavaScript
  // Javascript code to implement the approach 

  // Function to find the matrix A from B
  function solve(arr) {
      let n = arr.length;
      let m = arr[0].length;

      // Set to store rows and columns 
      let row = new Set();
      let col = new Set();

      let original = arr;

      // first find rows and columns containing 1 
      // and insert into set 
      for (let i = 0; i < n; i++) {
          for (let j = 0; j < m; j++) {
              if (arr[i][j]) {
                  row.add(i);
                  col.add(j);
              }
          }
      }
      // Set 1 to every row 
      for (let it of row) {
          for (let i = 0; i < m; i++) {
              arr[it][i] = 1;
          }
      }
      // Set 1 to every column 
      for (let it of col) {
          for (let i = 0; i < n; i++) {
              arr[i][it] = 1;
          }
      }
      var result = JSON.parse(JSON.stringify(arr));

      row.clear();
      col.clear();

      // first find rows and columns containing 0
      // and insert into set
      for (let i = 0; i < n; i++) {
          for (let j = 0; j < m; j++) {
              if (!arr[i][j]) {
                  row.add(i);
                  col.add(j);
              }
          }
      }

      // Set 0 to every row
      for (let it of row) {
          for (let i = 0; i < m; i++) {
              arr[it][i] = 0;
          }
      }

      // Set 0 to every column
      for (let it of col) {
          for (let i = 0; i < n; i++) {
              arr[i][it] = 0;
          }
      }
      // If the modified matrix and original matrix is not equal then print -1 
      if (JSON.stringify(arr) != JSON.stringify(original)) 
          console.log("-1");
      // else print the matrix res 
      else {
          for (var i = 0; i < n; i++) {
              for (var j = 0; j < m; j++) {
                  process.stdout.write(result[i][j] + " ");
              }
              console.log();
          }
      }
  }

  // Driver Code

  let v = [
      [1, 0, 1],
      [0, 0, 0]
  ];

  solve(v);

  // This code is contributed by Tapesh(tapeshdua420)

Output
1 1 1 
1 0 1 

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


Next Article
Practice Tags :

Similar Reads