Open In App

A Boolean Matrix Question

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given a boolean matrix mat[M][N] of size M X N, modify it such that if a matrix cell mat[i][j] is 1 (or true) then make all the cells of ith row and jth column as 1. 

Examples:

Input: {{1, 0},
           {0, 0}}
Output: {{1, 1}
              {1, 0}}
Input: {{0, 0, 0},
            {0, 0, 1}}
Output: {{0, 0, 1},
               {1, 1, 1}}
 

Input: {{1, 0, 0, 1},
           {0, 0, 1, 0},
          {0, 0, 0, 0}}
Output: {{1, 1, 1, 1},
               {1, 1, 1, 1},
              {1, 0, 1, 1}}

Recommended Practice

A Boolean Matrix Question using Brute Force:

Approach: Using brute force

Assuming all the elements in the matrix are non-negative. Traverse through the matrix and if you find an element with value 1, then change all the elements in its row and column to -1, except when an element is 1. The reason for not changing other elements to 1, but -1, is because that might affect other columns and rows. Now traverse through the matrix again and if an element is -1 change it to 1, which will be the answer.

C++




#include<bits/stdc++.h>
 
using namespace std;
 
void setZeroes(vector < vector < int >> & matrix) {
  int rows = matrix.size(), cols = matrix[0].size();
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      if (matrix[i][j] == 1) {
 
        int ind = i - 1;
        while (ind >= 0) {
          if (matrix[ind][j] != 1) {
            matrix[ind][j] = -1;
          }
          ind--;
        }
        ind = i + 1;
        while (ind < rows) {
          if (matrix[ind][j] != 1) {
            matrix[ind][j] = -1;
          }
          ind++;
        }
        ind = j - 1;
        while (ind >= 0) {
          if (matrix[i][ind] != 1) {
            matrix[i][ind] = -1;
 
          }
          ind--;
        }
        ind = j + 1;
        while (ind < cols) {
          if (matrix[i][ind] != 1) {
            matrix[i][ind] = -1;
 
          }
          ind++;
        }
      }
    }
  }
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      if (matrix[i][j] < 0) {
        matrix[i][j] = 1;
      }
    }
  }
 
}
 
int main() {
  vector < vector < int >> arr;
  arr = {{1, 0, 2, 1}, {3, 4, 5, 2}, {0, 3, 0, 5}};
  setZeroes(arr);
  cout << "The Final Matrix is " << endl;
  for (int i = 0; i < arr.size(); i++) {
    for (int j = 0; j < arr[0].size(); j++) {
      cout << arr[i][j] << " ";
    }
    cout << "\n";
  }
}


Java




import java.util.*;
 
class Main {
 
    // Given an m x n matrix, if an element is 0, set its
    // entire row and column to 0.
    static void setZeroes(int[][] matrix)
    {
 
        int rows = matrix.length;
        int cols = matrix[0].length;
 
        // Iterate through each element of the matrix
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
 
                // If the element is 1, mark its
                // corresponding row and column using -1
                if (matrix[i][j] == 1) {
 
                    // Mark all elements in the same column
                    // as -1, except for other 1's
                    int ind = i - 1;
                    while (ind >= 0) {
                        if (matrix[ind][j] != 1) {
                            matrix[ind][j] = -1;
                        }
                        ind--;
                    }
                    ind = i + 1;
                    while (ind < rows) {
                        if (matrix[ind][j] != 1) {
                            matrix[ind][j] = -1;
                        }
                        ind++;
                    }
 
                    // Mark all elements in the same row as
                    // -1, except for other 1's
                    ind = j - 1;
                    while (ind >= 0) {
                        if (matrix[i][ind] != 1) {
                            matrix[i][ind] = -1;
                        }
                        ind--;
                    }
                    ind = j + 1;
                    while (ind < cols) {
                        if (matrix[i][ind] != 1) {
                            matrix[i][ind] = -1;
                        }
                        ind++;
                    }
                }
            }
        }
 
        // Iterate through the matrix again, setting all
        // -1's to 0
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (matrix[i][j] < 0) {
                    matrix[i][j] = 1;
                }
            }
        }
    }
 
    // Test the setZeroes function with a sample input
    public static void main(String[] args)
    {
        int[][] arr = { { 1, 0, 2, 1 },
                        { 3, 4, 5, 2 },
                        { 0, 3, 0, 5 } };
        setZeroes(arr);
        System.out.println("The Final Matrix is:");
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[0].length; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }
}


Python3




# Python equivalent of above code
 
# define a function to set the zeroes in the matrix
def setZeroes(matrix):
    # get the length of the matrix
    rows = len(matrix)
    cols = len(matrix[0])
 
    # Iterate through each element of the matrix
    for i in range(0, rows):
        for j in range(0, cols):
 
            # If the element is 1, mark its
            # corresponding row and column using -1
            if matrix[i][j] == 1:
 
                # Mark all elements in the same column
                # as -1, except for other 1's
                ind = i - 1
                while ind >= 0:
                    if matrix[ind][j] != 1:
                        matrix[ind][j] = -1
                    ind -= 1
 
                ind = i + 1
                while ind < rows:
                    if matrix[ind][j] != 1:
                        matrix[ind][j] = -1
                    ind += 1
 
                # Mark all elements in the same row as
                # -1, except for other 1's
                ind = j - 1
                while ind >= 0:
                    if matrix[i][ind] != 1:
                        matrix[i][ind] = -1
                    ind -= 1
 
                ind = j + 1
                while ind < cols:
                    if matrix[i][ind] != 1:
                        matrix[i][ind] = -1
                    ind += 1
 
    # Iterate through the matrix again, setting all
    # -1's to 0
    for i in range(0, rows):
        for j in range(0, cols):
            if matrix[i][j] < 0:
                matrix[i][j] = 1
 
# Test the setZeroes function with a sample input
if __name__ == "__main__":
    arr = [[1, 0, 2, 1],
           [3, 4, 5, 2],
           [0, 3, 0, 5]]
    setZeroes(arr)
    print("The Final Matrix is:")
    for i in range(len(arr)):
        for j in range(len(arr[0])):
            print(arr[i][j], end=" ")
        print()


C#




using System;
using System.Collections.Generic;
 
class Program {
 
    // Given an m x n matrix, if an element is 0, set its
    // entire row and column to 0.
    static void SetZeroes(List<List<int> > matrix)
    {
        int rows = matrix.Count, cols = matrix[0].Count;
 
        // Iterate through each element of the matrix
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
 
                // If the element is 1, mark its
                // corresponding row and column using -1
                if (matrix[i][j] == 1) {
 
                    // Mark all elements in the same column
                    // as -1, except for other 1's
                    int ind = i - 1;
                    while (ind >= 0) {
                        if (matrix[ind][j] != 1) {
                            matrix[ind][j] = -1;
                        }
                        ind--;
                    }
                    ind = i + 1;
                    while (ind < rows) {
                        if (matrix[ind][j] != 1) {
                            matrix[ind][j] = -1;
                        }
                        ind++;
                    }
 
                    // Mark all elements in the same row as
                    // -1, except for other 1's
                    ind = j - 1;
                    while (ind >= 0) {
                        if (matrix[i][ind] != 1) {
                            matrix[i][ind] = -1;
                        }
                        ind--;
                    }
                    ind = j + 1;
                    while (ind < cols) {
                        if (matrix[i][ind] != 1) {
                            matrix[i][ind] = -1;
                        }
                        ind++;
                    }
                }
            }
        }
 
        // Iterate through the matrix again, setting all
        // -1's to 0
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (matrix[i][j] < 0) {
                    matrix[i][j] = 1;
                }
            }
        }
    }
 
    // Test the setZeroes function with a sample input
    static void Main(string[] args)
    {
        List<List<int> > arr = new List<List<int> >{
            new List<int>{ 1, 0, 2, 1 },
            new List<int>{ 3, 4, 5, 2 },
            new List<int>{ 0, 3, 0, 5 }
        };
        SetZeroes(arr);
        Console.WriteLine("The Final Matrix is ");
        for (int i = 0; i < arr.Count; i++) {
            for (int j = 0; j < arr[0].Count; j++) {
                Console.Write(arr[i][j] + " ");
            }
            Console.WriteLine();
        }
    }
}


Javascript




function setZeroes(matrix) {
  const rows = matrix.length;
  const cols = matrix[0].length;
 
  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      if (matrix[i][j] === 1) {
        let ind = i - 1;
        while (ind >= 0) {
          if (matrix[ind][j] !== 1) {
            matrix[ind][j] = -1;
          }
          ind--;
        }
 
        ind = i + 1;
        while (ind < rows) {
          if (matrix[ind][j] !== 1) {
            matrix[ind][j] = -1;
          }
          ind++;
        }
 
        ind = j - 1;
        while (ind >= 0) {
          if (matrix[i][ind] !== 1) {
            matrix[i][ind] = -1;
          }
          ind--;
        }
 
        ind = j + 1;
        while (ind < cols) {
          if (matrix[i][ind] !== 1) {
            matrix[i][ind] = -1;
          }
          ind++;
        }
      }
    }
  }
 
  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      if (matrix[i][j] < 0) {
        matrix[i][j] = 1;
      }
    }
  }
}
 
function printMatrix(matrix) {
  for (let i = 0; i < matrix.length; i++) {
    console.log(matrix[i].join(' '));
  }
}
 
// Main
const arr = [
  [1, 0, 2, 1],
  [3, 4, 5, 2],
  [0, 3, 0, 5]
];
setZeroes(arr);
console.log("The Final Matrix is:");
printMatrix(arr);


Output

The Final Matrix is 
1 1 1 1 
1 4 5 1 
1 3 0 1 

Time Complexity:O((N*M)*(N + M)). O(N*M) for traversing through each element and (N+M)for traversing to row and column of elements having value 1.
Space Complexity:O(1)

Another Approach:

Follow the steps below to solve the problem

  • Create two temporary arrays row[M] and col[N]. Initialize all values of row[] and col[] as 0. 
  • Traverse the input matrix mat[M][N]. If you see an entry mat[i][j] as true, then mark row[i] and col[j] as true. 
  • Traverse the input matrix mat[M][N] again. For each entry mat[i][j], check the values of row[i] and col[j]. If any of the two values (row[i] or col[j]) is true, then mark mat[i][j] as true.

Below is the implementation of the above approach:

C++




// C++ Code For A Boolean Matrix Question
#include <bits/stdc++.h>
 
using namespace std;
#define R 3
#define C 4
 
void modifyMatrix(bool mat[R][C])
{
    bool row[R];
    bool col[C];
 
    int i, j;
 
    /* Initialize all values of row[] as 0 */
    for (i = 0; i < R; i++)
        row[i] = 0;
 
    /* Initialize all values of col[] as 0 */
    for (i = 0; i < C; i++)
        col[i] = 0;
 
    // Store the rows and columns to be marked as
    // 1 in row[] and col[] arrays respectively
    for (i = 0; i < R; i++) {
        for (j = 0; j < C; j++) {
            if (mat[i][j] == 1) {
                row[i] = 1;
                col[j] = 1;
            }
        }
    }
 
    // Modify the input matrix mat[] using the
    // above constructed row[] and col[] arrays
    for (i = 0; i < R; i++)
        for (j = 0; j < C; j++)
            if (row[i] == 1 || col[j] == 1)
                mat[i][j] = 1;
}
 
/* A utility function to print a 2D matrix */
void printMatrix(bool mat[R][C])
{
    int i, j;
    for (i = 0; i < R; i++) {
        for (j = 0; j < C; j++)
            cout << mat[i][j];
        cout << endl;
    }
}
 
// Driver Code
int main()
{
    bool mat[R][C] = { { 1, 0, 0, 1 },
                       { 0, 0, 1, 0 },
                       { 0, 0, 0, 0 } };
 
    cout << "Input Matrix \n";
    printMatrix(mat);
    modifyMatrix(mat);
    printf("Matrix after modification \n");
    printMatrix(mat);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


C




// C Code For A Boolean Matrix Question
#include <stdbool.h>
#include <stdio.h>
 
#define R 3
#define C 4
 
void modifyMatrix(bool mat[R][C])
{
    bool row[R];
    bool col[C];
 
    int i, j;
 
    /* Initialize all values of row[] as 0 */
    for (i = 0; i < R; i++)
        row[i] = 0;
 
    /* Initialize all values of col[] as 0 */
    for (i = 0; i < C; i++)
        col[i] = 0;
 
    // Store the rows and columns to be marked as
    // 1 in row[] and col[] arrays respectively
    for (i = 0; i < R; i++) {
        for (j = 0; j < C; j++) {
            if (mat[i][j] == 1) {
                row[i] = 1;
                col[j] = 1;
            }
        }
    }
 
    // Modify the input matrix mat[] using the
    // above constructed row[] and col[] arrays
    for (i = 0; i < R; i++)
        for (j = 0; j < C; j++)
            if (row[i] == 1 || col[j] == 1)
                mat[i][j] = 1;
}
 
/* A utility function to print a 2D matrix */
void printMatrix(bool mat[R][C])
{
    int i, j;
    for (i = 0; i < R; i++) {
        for (j = 0; j < C; j++)
            printf("%d ", mat[i][j]);
        printf("\n");
    }
}
 
// Driver Code
int main()
{
    bool mat[R][C] = { { 1, 0, 0, 1 },
                       { 0, 0, 1, 0 },
                       { 0, 0, 0, 0 } };
 
    printf("Input Matrix \n");
    printMatrix(mat);
    modifyMatrix(mat);
    printf("Matrix after modification \n");
    printMatrix(mat);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Java




// Java Code For A Boolean Matrix Question
import java.io.*;
 
class GFG {
    public static void modifyMatrix(int mat[][], int R,
                                    int C)
    {
        int row[] = new int[R];
        int col[] = new int[C];
        int i, j;
 
        /* Initialize all values of row[] as 0 */
        for (i = 0; i < R; i++)
            row[i] = 0;
 
        /* Initialize all values of col[] as 0 */
        for (i = 0; i < C; i++)
            col[i] = 0;
 
        /* Store the rows and columns to be marked as
        1 in row[] and col[] arrays respectively */
        for (i = 0; i < R; i++) {
            for (j = 0; j < C; j++) {
                if (mat[i][j] == 1) {
                    row[i] = 1;
                    col[j] = 1;
                }
            }
        }
 
        /* Modify the input matrix mat[] using the
        above constructed row[] and col[] arrays */
        for (i = 0; i < R; i++)
            for (j = 0; j < C; j++)
                if (row[i] == 1 || col[j] == 1)
                    mat[i][j] = 1;
    }
 
    /* A utility function to print a 2D matrix */
    public static void printMatrix(int mat[][], int R,
                                   int C)
    {
        int i, j;
        for (i = 0; i < R; i++) {
            for (j = 0; j < C; j++)
                System.out.print(mat[i][j] + " ");
            System.out.println();
        }
    }
 
    /* Driver program to test above functions */
    public static void main(String[] args)
    {
        int mat[][] = {
            { 1, 0, 0, 1 },
            { 0, 0, 1, 0 },
            { 0, 0, 0, 0 },
        };
 
        System.out.println("Matrix Initially");
        printMatrix(mat, 3, 4);
        modifyMatrix(mat, 3, 4);
        System.out.println("Matrix after modification");
        printMatrix(mat, 3, 4);
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Python3




# Python3 Code For A Boolean Matrix Question
R = 3
C = 4
 
 
def modifyMatrix(mat):
    row = [0] * R
    col = [0] * C
 
    # Initialize all values of row[] as 0
    for i in range(0, R):
        row[i] = 0
 
    # Initialize all values of col[] as 0
    for i in range(0, C):
        col[i] = 0
 
    # Store the rows and columns to be marked
    # as 1 in row[] and col[] arrays respectively
    for i in range(0, R):
 
        for j in range(0, C):
            if (mat[i][j] == 1):
                row[i] = 1
                col[j] = 1
 
    # Modify the input matrix mat[] using the
    # above constructed row[] and col[] arrays
    for i in range(0, R):
 
        for j in range(0, C):
            if (row[i] == 1 or col[j] == 1):
                mat[i][j] = 1
 
# A utility function to print a 2D matrix
 
 
def printMatrix(mat):
    for i in range(0, R):
 
        for j in range(0, C):
            print(mat[i][j], end=" ")
        print()
 
 
# Driver Code
mat = [[1, 0, 0, 1],
       [0, 0, 1, 0],
       [0, 0, 0, 0]]
 
print("Input Matrix")
printMatrix(mat)
 
modifyMatrix(mat)
 
print("Matrix after modification")
printMatrix(mat)
 
# This code is contributed by Nikita Tiwari.


C#




// C# Code For A Boolean
// Matrix Question
using System;
 
class GFG {
    public static void modifyMatrix(int[, ] mat, int R,
                                    int C)
    {
        int[] row = new int[R];
        int[] col = new int[C];
        int i, j;
 
        /* Initialize all values
        of row[] as 0 */
        for (i = 0; i < R; i++) {
            row[i] = 0;
        }
 
        /* Initialize all values
        of col[] as 0 */
        for (i = 0; i < C; i++) {
            col[i] = 0;
        }
 
        /* Store the rows and columns
        to be marked as 1 in row[]
        and col[] arrays respectively */
        for (i = 0; i < R; i++) {
            for (j = 0; j < C; j++) {
                if (mat[i, j] == 1) {
                    row[i] = 1;
                    col[j] = 1;
                }
            }
        }
 
        /* Modify the input matrix
        mat[] using the above
        constructed row[] and
        col[] arrays */
        for (i = 0; i < R; i++) {
            for (j = 0; j < C; j++) {
                if (row[i] == 1 || col[j] == 1) {
                    mat[i, j] = 1;
                }
            }
        }
    }
 
    /* A utility function to
    print a 2D matrix */
    public static void printMatrix(int[, ] mat, int R,
                                   int C)
    {
        int i, j;
        for (i = 0; i < R; i++) {
            for (j = 0; j < C; j++) {
                Console.Write(mat[i, j] + " ");
            }
            Console.WriteLine();
        }
    }
 
    // Driver code
    static public void Main()
    {
        int[, ] mat = { { 1, 0, 0, 1 },
                        { 0, 0, 1, 0 },
                        { 0, 0, 0, 0 } };
 
        Console.WriteLine("Matrix Initially");
 
        printMatrix(mat, 3, 4);
 
        modifyMatrix(mat, 3, 4);
        Console.WriteLine("Matrix after "
                          + "modification");
        printMatrix(mat, 3, 4);
    }
}
 
// This code is contributed by ajit


Javascript




<script>
 
// Javascript Code For A Boolean Matrix Question
     
    function modifyMatrix(mat,R,C)
    {
        let row=new Array(R);
        let col = new Array(C);
         
        /* Initialize all values of row[] as 0 */
        for (i = 0; i < R; i++)
        {
            row[i] = 0;
        }
         
        /* Initialize all values of col[] as 0 */
        for (i = 0; i < C; i++)
        {
            col[i] = 0;
             
        }
         
        /* Store the rows and columns to be marked as
        1 in row[] and col[] arrays respectively */
        for (i = 0; i < R; i++)
        {
            for (j = 0; j < C; j++)
            {
                if (mat[i][j] == 1)
                {
                    row[i] = 1;
                    col[j] = 1;
                }
            }
        }
         
        /* Modify the input matrix mat[] using the
        above constructed row[] and col[] arrays */
        for (i = 0; i < R; i++)
        {
            for (j = 0; j < C; j++)
            {
                if ( row[i] == 1 || col[j] == 1 )
                {
                    mat[i][j] = 1;
                }
            }
        }
    }
     
    /* A utility function to print a 2D matrix */
    function printMatrix(mat,R,C)
    {
        let i, j;
        for (i = 0; i < R; i++)
        {
            for (j = 0; j < C; j++)
            {
                document.write(mat[i][j]+ " ");
            }
            document.write("<br>");
        }
    }
     
    /* Driver program to test above functions */
     
    let mat = [[1, 0, 0, 1],[0, 0, 1, 0],[0, 0, 0, 0]];
    document.write("Matrix Initially <br>")
    printMatrix(mat, 3, 4);
    modifyMatrix(mat, 3, 4);
    document.write("Matrix after modification n <br>");
    printMatrix(mat, 3, 4);
     
    // This code is contributed by avanitrachhadiya2155
     
</script>


PHP




<?php
// PHP Code For A Boolean
// Matrix Question
$R = 3;
$C = 4;
 
function modifyMatrix(&$mat)
{
    global $R,$C;
    $row = array();
    $col = array();
 
    /* Initialize all values
       of row[] as 0 */
    for ($i = 0; $i < $R; $i++)
    {
        $row[$i] = 0;
    }
 
 
    /* Initialize all values
       of col[] as 0 */
    for ($i = 0; $i < $C; $i++)
    {
        $col[$i] = 0;
    }
 
 
    /* Store the rows and columns
       to be marked as 1 in row[]
       and col[] arrays respectively */
    for ($i = 0; $i < $R; $i++)
    {
        for ($j = 0; $j < $C; $j++)
        {
            if ($mat[$i][$j] == 1)
            {
                $row[$i] = 1;
                $col[$j] = 1;
            }
        }
    }
 
    /* Modify the input matrix mat[]
       using the above constructed
       row[] and col[] arrays */
    for ($i = 0; $i < $R; $i++)
    {
        for ($j = 0; $j < $C; $j++)
        {
            if ($row[$i] == 1 ||
                $col[$j] == 1 )
            {
                $mat[$i][$j] = 1;
            }
        }
    }
}
 
/* A utility function to
   print a 2D matrix */
function printMatrix(&$mat)
{
    global $R, $C;
    for ($i = 0; $i < $R; $i++)
    {
        for ($j = 0; $j < $C; $j++)
        {
            echo $mat[$i][$j] . " ";
        }
        echo "\n";
    }
}
 
// Driver code
$mat = array(array(1, 0, 0, 1),
             array(0, 0, 1, 0),
             array(0, 0, 0, 0));
 
echo "Input Matrix \n";
printMatrix($mat);
 
modifyMatrix($mat);
 
echo "Matrix after modification \n";
printMatrix($mat);
 
// This code is contributed
// by ChitraNayal
?>


Output

Input Matrix 
1001
0010
0000
Matrix after modification 
1111
1111
1011

Time Complexity: O(M*N), Traversing over the matrix two times.
Auxiliary Space: O(M + N), Taking two arrays one of size M and another of size N.

Thanks to Dixit Sethi for suggesting this method. 

A Boolean Matrix Question using O(1) Space:

Intuition: Instead of taking two dummy arrays we can use the first row and column of the matrix for the same work. This will help to reduce the space complexity of the problem. While traversing for the second time the first row and column will be computed first, which will affect the values of further elements that’s why we traversing in the reverse direction.

Approach: Instead of taking two separate dummy arrays, take the first row and column of the matrix as the array for checking whether the particular column or row has the value 1 or not.Since matrix[0][0] are overlapping.Therefore take separate variable col0(say) to check if the 0th column has 1 or not and use matrix[0][0] to check if the 0th row has 1 or not. Now traverse from the last element to the first element and check if matrix[i][0]==1 || matrix[0][j]==1 and if true set matrix[i][j]=1, else continue.

Below is the implementation of above approach:

C++




#include<bits/stdc++.h>
using namespace std;
void setZeroes(vector < vector < int >> & matrix) {
  int col0 = 0, rows = matrix.size(), cols = matrix[0].size();
  for (int i = 0; i < rows; i++) {
    //checking if 0 is present in the 0th column or not
    if (matrix[i][0] == 1) col0 = 1;
    for (int j = 1; j < cols; j++) {
      if (matrix[i][j] == 1) {
        matrix[i][0] = 1;
        matrix[0][j] = 1;
      }
    }
  }
  //traversing in the reverse direction and
  //checking if the row or col has 0 or not
  //and setting values of matrix accordingly.
  for (int i = rows - 1; i >= 0; i--) {
    for (int j = cols - 1; j >= 1; j--) {
      if (matrix[i][0] == 1 || matrix[0][j] == 1) {
        matrix[i][j] = 1;
      }
    }
    if (col0 == 1) {
      matrix[i][0] = 1;
    }
 
  }
 
}
 
int main() {
  vector < vector < int >> arr;
  arr = {{1, 0, 2, 1}, {3, 4, 5, 2}, {0, 3, 0, 5}};
  setZeroes(arr);
  cout<<"The Final Matrix is "<<endl;
  for (int i = 0; i < arr.size(); i++) {
    for (int j = 0; j < arr[0].size(); j++) {
      cout << arr[i][j] << " ";
    }
    cout << "\n";
  }
}


C




#include <stdbool.h>
#include <stdio.h>
 
#define R 3
#define C 4
 
void modifyMatrix(int mat[R][C])
{
    // variables to check if there are any 1
    // in first row and column
    bool row_flag = false;
    bool col_flag = false;
 
    // updating the first row and col if 1
    // is encountered
    for (int i = 0; i < R; i++) {
        for (int j = 0; j < C; j++) {
            if (i == 0 && mat[i][j] == 1)
                row_flag = true;
 
            if (j == 0 && mat[i][j] == 1)
                col_flag = true;
 
            if (mat[i][j] == 1) {
                mat[0][j] = 1;
                mat[i][0] = 1;
            }
        }
    }
 
    // Modify the input matrix mat[] using the
    // first row and first column of Matrix mat
    for (int i = 1; i < R; i++)
        for (int j = 1; j < C; j++)
            if (mat[0][j] == 1 || mat[i][0] == 1)
                mat[i][j] = 1;
 
    // modify first row if there was any 1
    if (row_flag == true)
        for (int i = 0; i < C; i++)
            mat[0][i] = 1;
 
    // modify first col if there was any 1
    if (col_flag == true)
        for (int i = 0; i < R; i++)
            mat[i][0] = 1;
}
 
/* A utility function to print a 2D matrix */
void printMatrix(int mat[R][C])
{
    for (int i = 0; i < R; i++) {
        for (int j = 0; j < C; j++)
            printf("%d ", mat[i][j]);
        printf("\n");
    }
}
 
// Driver function to test the above function
int main()
{
 
    int mat[R][C] = { { 1, 0, 0, 1 },
                      { 0, 0, 1, 0 },
                      { 0, 0, 0, 0 } };
 
    printf("Input Matrix :\n");
    printMatrix(mat);
    modifyMatrix(mat);
    printf("Matrix After Modification :\n");
    printMatrix(mat);
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Java




import java.io.*;
class GFG {
    public static void modifyMatrix(int mat[][])
    {
        // variables to check if there are any 1
        // in first row and column
        boolean row_flag = false;
        boolean col_flag = false;
 
        // updating the first row and col if 1
        // is encountered
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[0].length; j++) {
                if (i == 0 && mat[i][j] == 1)
                    row_flag = true;
 
                if (j == 0 && mat[i][j] == 1)
                    col_flag = true;
 
                if (mat[i][j] == 1) {
 
                    mat[0][j] = 1;
                    mat[i][0] = 1;
                }
            }
        }
 
        // Modify the input matrix mat[] using the
        // first row and first column of Matrix mat
        for (int i = 1; i < mat.length; i++)
            for (int j = 1; j < mat[0].length; j++)
                if (mat[0][j] == 1 || mat[i][0] == 1)
                    mat[i][j] = 1;
 
        // modify first row if there was any 1
        if (row_flag == true)
            for (int i = 0; i < mat[0].length; i++)
                mat[0][i] = 1;
 
        // modify first col if there was any 1
        if (col_flag == true)
            for (int i = 0; i < mat.length; i++)
                mat[i][0] = 1;
    }
 
    /* A utility function to print a 2D matrix */
    public static void printMatrix(int mat[][])
    {
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[0].length; j++)
                System.out.print(mat[i][j] + " ");
            System.out.println("");
        }
    }
 
    // Driver function to test the above function
    public static void main(String args[])
    {
        int mat[][] = { { 1, 0, 0, 1 },
                        { 0, 0, 1, 0 },
                        { 0, 0, 0, 0 } };
 
        System.out.println("Input Matrix :");
        printMatrix(mat);
        modifyMatrix(mat);
        System.out.println("Matrix After Modification :");
        printMatrix(mat);
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Python3




# Python3 Code For A Boolean Matrix Question
def modifyMatrix(mat):
 
    # variables to check if there are any 1
    # in first row and column
    row_flag = False
    col_flag = False
 
    # updating the first row and col
    # if 1 is encountered
    for i in range(0, len(mat)):
 
        for j in range(0, len(mat)):
            if (i == 0 and mat[i][j] == 1):
                row_flag = True
 
            if (j == 0 and mat[i][j] == 1):
                col_flag = True
 
            if (mat[i][j] == 1):
                mat[0][j] = 1
                mat[i][0] = 1
 
    # Modify the input matrix mat[] using the
    # first row and first column of Matrix mat
    for i in range(1, len(mat)):
 
        for j in range(1, len(mat) + 1):
            if (mat[0][j] == 1 or mat[i][0] == 1):
                mat[i][j] = 1
 
    # modify first row if there was any 1
    if (row_flag == True):
        for i in range(0, len(mat)):
            mat[0][i] = 1
 
    # modify first col if there was any 1
    if (col_flag == True):
        for i in range(0, len(mat)):
            mat[i][0] = 1
 
# A utility function to print a 2D matrix
 
 
def printMatrix(mat):
 
    for i in range(0, len(mat)):
        for j in range(0, len(mat) + 1):
            print(mat[i][j], end="")
 
        print()
 
 
# Driver Code
mat = [[1, 0, 0, 1],
       [0, 0, 1, 0],
       [0, 0, 0, 0]]
 
print("Input Matrix :")
printMatrix(mat)
 
modifyMatrix(mat)
 
print("Matrix After Modification :")
printMatrix(mat)
 
# This code is contributed by Nikita tiwari.


C#




// C# Code For A Boolean
// Matrix Question
using System;
 
class GFG {
    public static void modifyMatrix(int[, ] mat)
    {
 
        // variables to check
        // if there are any 1
        // in first row and column
        bool row_flag = false;
        bool col_flag = false;
 
        // updating the first
        // row and col if 1
        // is encountered
        for (int i = 0; i < mat.GetLength(0); i++) {
            for (int j = 0; j < mat.GetLength(1); j++) {
                if (i == 0 && mat[i, j] == 1)
                    row_flag = true;
 
                if (j == 0 && mat[i, j] == 1)
                    col_flag = true;
 
                if (mat[i, j] == 1) {
                    mat[0, j] = 1;
                    mat[i, 0] = 1;
                }
            }
        }
 
        // Modify the input matrix mat[]
        // using the first row and first
        // column of Matrix mat
        for (int i = 1; i < mat.GetLength(0); i++) {
            for (int j = 1; j < mat.GetLength(1); j++) {
 
                if (mat[0, j] == 1 || mat[i, 0] == 1) {
                    mat[i, j] = 1;
                }
            }
        }
 
        // modify first row
        // if there was any 1
        if (row_flag == true) {
            for (int i = 0; i < mat.GetLength(1); i++) {
                mat[0, i] = 1;
            }
        }
 
        // modify first col if
        // there was any 1
        if (col_flag == true) {
            for (int i = 0; i < mat.GetLength(0); i++) {
                mat[i, 0] = 1;
            }
        }
    }
 
    /* A utility function
    to print a 2D matrix */
    public static void printMatrix(int[, ] mat)
    {
        for (int i = 0; i < mat.GetLength(0); i++) {
            for (int j = 0; j < mat.GetLength(1); j++) {
                Console.Write(mat[i, j] + " ");
            }
            Console.Write("\n");
        }
    }
 
    // Driver Code
    public static void Main()
    {
        int[, ] mat = { { 1, 0, 0, 1 },
                        { 0, 0, 1, 0 },
                        { 0, 0, 0, 0 } };
 
        Console.Write("Input Matrix :\n");
        printMatrix(mat);
 
        modifyMatrix(mat);
 
        Console.Write("Matrix After "
                      + "Modification :\n");
        printMatrix(mat);
    }
}
 
// This code is contributed
// by ChitraNayal


Javascript




<script>
 
function modifyMatrix(mat)
{
    // variables to check if there are any 1
        // in first row and column
        let row_flag = false;
        let col_flag = false;
                  
        // updating the first row and col if 1
        // is encountered
        for (let i = 0; i < mat.length; i++ ){
                for (let j = 0; j < mat[0].length; j++){
                        if (i == 0 && mat[i][j] == 1)
                            row_flag = true;
                          
                        if (j == 0 && mat[i][j] == 1)
                            col_flag = true;
                          
                        if (mat[i][j] == 1){
                              
                            mat[0][j] = 1;
                            mat[i][0] = 1;
                        }
                          
                    }
                }
                  
        // Modify the input matrix mat[] using the
        // first row and first column of Matrix mat
        for (let i = 1; i < mat.length; i ++){
                for (let j = 1; j < mat[0].length; j ++){
                          
                    if (mat[0][j] == 1 || mat[i][0] == 1){
                            mat[i][j] = 1;
                        }
                    }
                }
                  
        // modify first row if there was any 1
        if (row_flag == true){
            for (let i = 0; i < mat[0].length; i++){
                        mat[0][i] = 1;
                    }
                }
                  
        // modify first col if there was any 1
        if (col_flag == true){
            for (let i = 0; i < mat.length; i ++){
                        mat[i][0] = 1;
            }
        }
}
 
/* A utility function to print a 2D matrix */
function printMatrix(mat)
{
    for (let i = 0; i < mat.length; i ++){
            for (let j = 0; j < mat[0].length; j ++){
                document.write( mat[i][j] );
            }
                document.write("<br>");
        }
}
 
// Driver function to test the above function
let mat=[[1, 0, 0, 1],
                [0, 0, 1, 0],
                [0, 0, 0, 0]];
document.write("Input Matrix :<br>");
printMatrix(mat);
 
modifyMatrix(mat);
 
document.write("Matrix After Modification :<br>");
printMatrix(mat);
 
// This code is contributed by ab2127
 
</script>


PHP




<?php
// PHP Code For A Boolean
// Matrix Question
$R = 3;
$C = 4;
 
function modifyMatrix(&$mat)
{
    global $R, $C;
     
    // variables to check if
    // there are any 1 in
    // first row and column
    $row_flag = false;
    $col_flag = false;
 
    // updating the first
    // row and col if 1
    // is encountered
    for ($i = 0; $i < $R; $i++)
    {
        for ($j = 0; $j < $C; $j++)
        {
            if ($i == 0 && $mat[$i][$j] == 1)
                $row_flag = true;
 
            if ($j == 0 && $mat[$i][$j] == 1)
                $col_flag = true;
 
            if ($mat[$i][$j] == 1)
            {
                $mat[0][$j] = 1;
                $mat[$i][0] = 1;
            }
        }
    }
 
    // Modify the input matrix
    // mat[] using the first
    // row and first column of
    // Matrix mat
    for ($i = 1; $i < $R; $i++)
    {
        for ($j = 1; $j < $C; $j++)
        {
            if ($mat[0][$j] == 1 ||
                $mat[$i][0] == 1)
            {
                $mat[$i][$j] = 1;
            }
        }
    }
 
    // modify first row
    // if there was any 1
    if ($row_flag == true)
    {
        for ($i = 0; $i < $C; $i++)
        {
            $mat[0][$i] = 1;
        }
    }
 
    // modify first col
    // if there was any 1
    if ($col_flag == true)
    {
        for ($i = 0; $i < $R; $i++)
        {
            $mat[$i][0] = 1;
        }
    }
}
 
/* A utility function
to print a 2D matrix */
function printMatrix(&$mat)
{
    global $R, $C;
    for ($i = 0; $i < $R; $i++)
    {
        for ($j = 0; $j < $C; $j++)
        {
            echo $mat[$i][$j]." ";
        }
        echo "\n";
    }
}
 
// Driver Code
$mat = array(array(1, 0, 0, 1 ),
             array(0, 0, 1, 0 ),
             array(0, 0, 0, 0 ));
 
echo "Input Matrix :\n";
printMatrix($mat);
 
modifyMatrix($mat);
 
echo "Matrix After Modification :\n";
printMatrix($mat);
 
// This code is contributed
// by ChitraNayal
?>


Output

Input Matrix :
1 0 0 1 
0 0 1 0 
0 0 0 0 
Matrix After Modification :
1 1 1 1 
1 1 1 1 
1 0 1 1 

Time Complexity: O(M*N), Traversing over the matrix two times.
Auxiliary Space: O(1)

 Thanks to Sidh for suggesting this method. 



Last Updated : 22 Aug, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads