Open In App

Min operations for each index to make element at that cell equal to 1

Last Updated : 03 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a matrix M[][] having R rows and C columns, the task is to return a matrix X[][] in which X[i][j] represents the number of minimum operations required to convert M[i][j] into 1 else print Not Possible. Where the operations are defined as:

  • Select any two rows let say R1 and R2 and update R1 with (R1 | R2) for i (1 <= i <= Row.length) 
  • Select any two columns let say C1 and C2 and update C1 with (C1 | C2) for i (1 <= i <= Column.length)

Note: Only one operation should be used at a time.  

Examples:

Input: R = 2, C = 2, M[][]: {{0, 1}, {1, 0}}
Output: 1 0
0 1
Explanation: Below steps defined each cell of the output Matrix, Let’s say the Output matrix is X[][]: 

There are only two rows and columns in M[][] as R1 and R2 and C1 and C2. 

  • X[1][1]: 
    •  R1 = {0 1} 
    • R2 = {1 0}. 
    • Bitwise OR of R1 and R2 at respective indices = {0|1, 1|0} = {1, 1}. Then update R1 of M[][] with calculated OR vales. Then M[][] is: {{1, 1}, {1, 0}}

Only one operation is required to convert M[1][1] into 1.Thus X[1][1] = 1.  

  • X[1][2]:
    • As input M[1][2] is already equal to 1. Therefore, there is no need to perform the operation. Hence, X[1][2] = 0.
  • X[2][1]:
    • As input Matrix[2][1] is already equal to 1. Therefore, there is no need to perform the operation. Hence, X[1][2] = 0
  • Out[2][2]: 
    • C1 = {1 0}
    • C2 = {1 1}
    • Bitwise OR of C1 and C2 at respective indices = {1|1, 0|1} = {1, 1}. Then update C1 of M[][] as calculated OR vales. Then M[][] is: {{1, 1}, {1, 1}}

Only one operation is required to convert M[2][2] into 1. Thus X[2][2] = 1

Now, All the elements are 1 in M[][]. All the minimum number of operations are shown in X[][].

Input: R = 3, C = 3, M[][]= {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}
Output: Not Possible
Explanation: It can be verified that all the elements which are 0 in the given matrix can’t be made equal to 1. Therefore, the output is Not Possible.

Approach: Implement the idea below to solve the problem:

 The problem is observation based and can be solve by implementing those observations. It should be noted that we can’t make all the elements 1, if and only if, all the elements in the given matrix are zero.

Steps were taken to solve the problem:

  • Create two arrays row[] and col[] of size N and M respectively.
  • Initialize String S of size N. 
  • Run a loop for i=0 to less than N:
    •  Run a loop for j=0 to less than M and follow the below-mentioned steps under the scope of the loop:
      • if( S[i].charAt[j]==’1′ ) then update row[i] and col[j] to 1.
  • Create two integer variables sum and sum1 for calculating the sum of the row and column elements respectively.
  • Initialize sum and sum1 with the sum of elements
  • If ( sum+sum1 == 0 ), Then the output is Not Possible else follow the below-mentioned steps:
    •  Run two nested loops for i=0 and j=0 to less than N and less than M respectively and follow the below-mentioned steps:
      • if ( S[i].charAt(j) == ‘1’ ) then output 0.
      • else:
        • if ( row[i]==1 || col[j]==1 ) then output 1 else output 2.

Below is the code to implement the approach:

C++




// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print minimum
// number of operations
void Printer(int n, int m, vector <string>& arr)
{
  // Arrays for storing minimum
  // operations for elements of
  // rows are columns
  int row[n];
  int col[m];
 
  // string vector for
  // containing rows of
  // input matrix
  vector <string> s(n);
 
  // Loop for initializing S with
  // rows of input matrix
  for (int i = 0; i < n; i++) {
    s[i] = arr[i];
 
    // Loop for traversing S
    for (int j = 0; j < m; j++) {
      if (s[i][j] == '1') {
        row[i] = 1;
        col[j] = 1;
      }
    }
  }
 
  // Variables for calculating
  // sum of rows and
  // column elements
  int sum = 0;
  int sum1 = 0;
 
  // boolean Flag
  bool flag = false;
 
  // Loop for traversing
  // column and rows
  for (int i = 0; i < n; i++)
    sum += row[i];
  for (int i = 0; i < m; i++)
    sum1 += col[i];
 
  // Condition when all the elements
  // of rows and column will be
  // equal to 0 In this condition,
  // We can't make all the elements
  // of given matrix to 1
  if (sum + sum1 == 0) {
    cout << "Not Possible\n";
    flag = true;
  }
 
  // Condition when output
  // matrix is possible
  if (flag != true) {
 
    // Loops and statements for
    // printing output matrix
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < m; j++) {
        if (s[i][j] == '1') {
          cout << "0 ";
        }
        else {
          if (row[i] == 1 || col[j] == 1) {
            cout << "1 ";
          }
          else {
            cout << "2 ";
          }
        }
      }
      cout << endl;
    }
  }
}
 
int main()
{
 
  // Inputs
  int n = 2;
  int m = 3;
  vector <string> arr = { "000", "010" };
 
  // Function call
  Printer(n, m, arr);
}


Java




// Java code to implement the approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
    // Driver function
    public static void main(String[] args)
        throws java.lang.Exception
    {
 
        // Inputs
        int n = 2;
        int m = 3;
        String[] arr = { "000", "010" };
 
        // Function call
        Printer(n, m, arr);
    }
 
    // Function to print minimum
    // number of operations
    static void Printer(int n, int m, String[] arr)
    {
        // Arrays for stroing minimum
        // operations for elements of
        // rows are columns
        int[] row = new int[n];
        int[] col = new int[m];
 
        // String initialized for
        // containing rows of
        // input matrix
        String[] s = new String[n];
 
        // Loop for initializing S with
        // rows of input matrix
        for (int i = 0; i < n; i++) {
            s[i] = arr[i];
 
            // Loop for traversing S
            for (int j = 0; j < m; j++) {
                if (s[i].charAt(j) == '1') {
                    row[i] = 1;
                    col[j] = 1;
                }
            }
        }
 
        // Variables for calculating
        // sum of rows and
        // column elements
        int sum = 0;
        int sum1 = 0;
 
        // boolean Flag
        boolean flag = false;
 
        // Loop for traversing
        // column and rows
        for (int i = 0; i < n; i++)
            sum += row[i];
        for (int i = 0; i < m; i++)
            sum1 += col[i];
 
        // Condition when all the elements
        // of rows and column will be
        // equal to 0 In this condition,
        // We can't make all the elements
        // of given matrix to 1
        if (sum + sum1 == 0) {
            System.out.println("Not Possible");
            flag = true;
        }
 
        // Condition when output
        // matrix is possible
        if (flag != true) {
 
            // Loops and statements for
            // printing output matrix
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (s[i].charAt(j) == '1') {
                        System.out.print(0 + " ");
                    }
                    else {
                        if (row[i] == 1 || col[j] == 1) {
                            System.out.print(1 + " ");
                        }
                        else {
                            System.out.print(2 + " ");
                        }
                    }
                }
                System.out.print("\n");
            }
        }
    }
}


Python3




# Python code to implement the approach
 
# Function to print minimum
# number of operations
 
 
def Printer(n, m, arr):
 
    # Arrays for storing minimum
    # operations for elements of
    # rows and columns
    row = [0] * n
    col = [0] * m
 
    # List for containing rows of
    # input matrix
    s = []
 
    # Loop for initializing S with
    # rows of input matrix
    for i in range(n):
        s.append(arr[i])
 
        # Loop for traversing S
        for j in range(m):
            if s[i][j] == '1':
                row[i] = 1
                col[j] = 1
 
    # Variables for calculating
    # sum of rows and
    # column elements
    sum_ = 0
    sum1 = 0
 
    # boolean Flag
    flag = False
 
    # Loop for traversing
    # column and rows
    for i in range(n):
        sum_ += row[i]
    for i in range(m):
        sum1 += col[i]
 
    # Condition when all the elements
    # of rows and column will be
    # equal to 0 In this condition,
    # We can't make all the elements
    # of given matrix to 1
    if sum_ + sum1 == 0:
        print("Not Possible")
        flag = True
 
    # Condition when output
    # matrix is possible
    if not flag:
        # Loops and statements for
        # printing output matrix
        for i in range(n):
            for j in range(m):
                if s[i][j] == '1':
                    print("0 ", end="")
                else:
                    if row[i] == 1 or col[j] == 1:
                        print("1 ", end="")
                    else:
                        print("2 ", end="")
            print()
 
 
# Inputs
n = 2
m = 3
arr = ["000", "010"]
 
# Function call
Printer(n, m, arr)
 
# This code is contributed by Susobhan Akhuli


C#




using System;
using System.Collections.Generic;
 
class Solution {
     
    // Function to print minimum number of operations
    static void Printer(int n, int m, List<string> arr) {
         
        // Arrays for stroing minimum operations for elements of rows are columns
        int[] row = new int[n];
        int[] col = new int[m];
         
        // string vector for containing rows of input matrix
        List<string> s = new List<string>(n);
         
        // Loop for initializing S with rows of input matrix
        for (int i = 0; i < n; i++) {
            s.Add(arr[i]);
             
            // Loop for traversing S
            for (int j = 0; j < m; j++) {
                if (s[i][j] == '1') {
                    row[i] = 1;
                    col[j] = 1;
                }
            }
        }
         
        // Variables for calculating sum of rows and column elements
        int sum = 0;
        int sum1 = 0;
         
        // boolean Flag
        bool flag = false;
         
        // Loop for traversing column and rows
        for (int i = 0; i < n; i++)
            sum += row[i];
        for (int i = 0; i < m; i++)
            sum1 += col[i];
         
        // Condition when all the elements of rows and column will be equal to 0 In this condition, We can't make all the elements of given matrix to 1
        if (sum + sum1 == 0) {
            Console.WriteLine("Not Possible");
            flag = true;
        }
         
        // Condition when output matrix is possible
        if (flag != true) {
             
            // Loops and statements for printing output matrix
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (s[i][j] == '1') {
                        Console.Write("0 ");
                    }
                    else {
                        if (row[i] == 1 || col[j] == 1) {
                            Console.Write("1 ");
                        }
                        else {
                            Console.Write("2 ");
                        }
                    }
                }
                Console.WriteLine();
            }
        }
    }
     
    static void Main() {
         
        // Inputs
        int n = 2;
        int m = 3;
        List<string> arr = new List<string>() { "000", "010" };
         
        // Function call
        Printer(n, m, arr);
    }
}


Javascript




// JavaScript code to implement the approach
 
// Function to print minimum
// number of operations
function Printer(n, m, arr) {
    // Arrays for storing minimum
    // operations for elements of
    // rows and columns
    let row = new Array(n).fill(0);
    let col = new Array(m).fill(0);
     
    // string vector for
    // containing rows of
    // input matrix
    let s = [...arr];
     
    // Loop for initializing S with
    // rows of input matrix
    for (let i = 0; i < n; i++) {
         
        // Loop for traversing s
        for (let j = 0; j < m; j++) {
            if (s[i][j] === '1') {
                row[i] = 1;
                col[j] = 1;
            }
        }
    }
     
    // Variables for calculating
    // sum of rows and columns elements
    let sum = row.reduce((a, b) => a + b);
    let sum1 = col.reduce((a, b) => a + b);
     
    // Boolean flag
    let flag = false;
     
    // Condition when all the elements
    // of rows and column will be
    // equal to 0 In this condition,
    // We can't make all the elements
    // of given matrix to 1
    if (sum + sum1 === 0) {
        console.log("Not Possible");
        flag = true;
    }
     
    // Condition when output
    // matrix is possible
    if (!flag) {
         
        // Loops and statements for
        // printing output matrix
        for (let i = 0; i < n; i++) {
            for (let j = 0; j < m; j++) {
                if (s[i][j] === '1') {
                    process.stdout.write('0 ');
                }
                else {
                    if (row[i] === 1 || col[j] === 1) {
                        process.stdout.write('1 ');
                    }
                    else {
                        process.stdout.write('2 ');
                    }
                }
            }
            console.log();
        }
    }
}
 
// Driver code
let n = 2;
let m = 3;
let arr = ["000", "010"];
 
// Function call
Printer(n, m, arr);
 
// This code is contributed by prasad264


Output

2 1 2 
1 0 1 

Time Complexity: O(R*C)
Auxiliary Space: O(R*C)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads