A Boolean Matrix Question (original) (raw)

Given a boolean matrix **mat where each cell contains either 0 or 1, the task is to modify it such that if a matrix cell matrix[i][j] is 1 then all the cells in its **i th row and **j th column will **become 1.

**Examples:

**Input: [[1, 0],
[0, 0]]
**Output: [[1, 1],
[1, 0]]

**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]]

**[Naive Approach] By Marking the Matrix

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 zeros in its row and column to -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++ `

// C++ Code For Boolean Matrix Question // By Marking the Matrix

#include #include using namespace std;

void booleanMatrix(vector<vector>& mat) { int rows = mat.size(), cols = mat[0].size();

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        if (mat[i][j] == 1) {
          
              // Replace all the zeros in jth column by -1
              for (int idx = 0; idx < rows; idx++) {
                  if (mat[idx][j] == 0) {
                      mat[idx][j] = -1;
                }
            }
              
              // Replace all the zeros in ith row by -1
              for (int idx = 0; idx < cols; idx++) {
                  if (mat[i][idx] == 0) {
                      mat[i][idx] = -1;
                }
            }
        }
    }
}

  // Replace all the -1 by 1
for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        if (mat[i][j] == -1) {
            mat[i][j] = 1;
        }
    }
}

}

int main() { vector<vector> mat = {{1, 0, 0, 1}, {0, 0, 1, 0}, {0, 0, 0, 0}}; booleanMatrix(mat); for (const vector& row : mat) { for (int val : row) { cout << val << " "; } cout << endl; } return 0; }

Java

// Java Code For Boolean Matrix Question // By Marking the Matrix class GfG { static void booleanMatrix(int[][] mat) { int rows = mat.length, cols = mat[0].length;

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (mat[i][j] == 1) {
              
                // Replace all the zeros in jth column by -1
                for (int idx = 0; idx < rows; idx++) {
                    if (mat[idx][j] == 0) {
                        mat[idx][j] = -1;
                    }
                }

                // Replace all the zeros in ith row by -1
                for (int idx = 0; idx < cols; idx++) {
                    if (mat[i][idx] == 0) {
                        mat[i][idx] = -1;
                    }
                }
            }
        }
    }

    // Replace all the -1 by 1
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (mat[i][j] == -1) {
                mat[i][j] = 1;
            }
        }
    }
}

public static void main(String[] args) {
    int[][] mat = {{1, 0, 0, 1}, {0, 0, 1, 0}, {0, 0, 0, 0}};
    booleanMatrix(mat);
    for (int[] row : mat) {
        for (int val : row) {
            System.out.print(val + " ");
        }
        System.out.println();
    }
}

}

Python

python3 Code For Boolean Matrix Question

By Marking the Matrix

def booleanMatrix(mat): rows, cols = len(mat), len(mat[0])

for i in range(rows):
    for j in range(cols):
        if mat[i][j] == 1:
            # Replace all the zeros in jth column by -1
            for idx in range(rows):
                if mat[idx][j] == 0:
                    mat[idx][j] = -1

            # Replace all the zeros in ith row by -1
            for idx in range(cols):
                if mat[i][idx] == 0:
                    mat[i][idx] = -1

# Replace all the -1 by 1
for i in range(rows):
    for j in range(cols):
        if mat[i][j] == -1:
            mat[i][j] = 1

if name == "main": mat = [[1, 0, 0, 1], [0, 0, 1, 0], [0, 0, 0, 0]] booleanMatrix(mat) for row in mat: print(" ".join(map(str, row)))

C#

// C# Code For Boolean Matrix Question // By Marking the Matrix using System;

class GfG { static void booleanMatrix(int[, ] mat) { int rows = mat.GetLength(0), cols = mat.GetLength(1);

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (mat[i, j] == 1) {
              
                // Replace all the zeros in jth column
                // by -1
                for (int idx = 0; idx < rows; idx++) {
                    if (mat[idx, j] == 0) {
                        mat[idx, j] = -1;
                    }
                }

                // Replace all the zeros in ith row by
                // -1
                for (int idx = 0; idx < cols; idx++) {
                    if (mat[i, idx] == 0) {
                        mat[i, idx] = -1;
                    }
                }
            }
        }
    }

    // Replace all the -1 by 1
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (mat[i, j] == -1) {
                mat[i, j] = 1;
            }
        }
    }
}

static void Main() {
    int[, ] mat = { { 1, 0, 0, 1 },
                    { 0, 0, 1, 0 },
                    { 0, 0, 0, 0 } };
  
    booleanMatrix(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.WriteLine();
    }
}

}

JavaScript

// Javascript Code For Boolean Matrix Question // By Marking the Matrix function booleanMatrix(mat) { let rows = mat.length, cols = mat[0].length;

for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
        if (mat[i][j] === 1) {
        
            // Replace all the zeros in jth column by -1
            for (let idx = 0; idx < rows; idx++) {
                if (mat[idx][j] === 0) {
                    mat[idx][j] = -1;
                }
            }

            // Replace all the zeros in ith row by -1
            for (let idx = 0; idx < cols; idx++) {
                if (mat[i][idx] === 0) {
                    mat[i][idx] = -1;
                }
            }
        }
    }
}

// Replace all the -1 by 1
for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
        if (mat[i][j] === -1) {
            mat[i][j] = 1;
        }
    }
}

}

// Driver Code let mat = [[1, 0, 0, 1], [0, 0, 1, 0], [0, 0, 0, 0]]; booleanMatrix(mat); mat.forEach(row => { console.log(row.join(' ')); });

`

Output

1 1 1 1 1 1 1 1 1 0 1 1

**Time Complexity: O((n * m)*(n + m)) where n is number of rows and m is number of columns in given matrix.
O(n * m) for traversing through each element and (n+m) for traversing to row and column of matrix elements having value 1.
**Space Complexity: O(1)

**[Better Approach] Using Extra Space

The idea is to use **two temporary arrays, rowMarker[] and **colMarker[], to keep track of which rows and columns need to be updated.

Following are the steps for this approach

// C++ Code For Boolean Matrix Question // Using two extra arrays #include #include using namespace std;

void booleanMatrix(vector<vector>& mat) { int rows = mat.size(); int cols = mat[0].size();

// Arrays to keep track of rows and columns to be updated
vector<bool> rowMarker(rows, false);
vector<bool> colMarker(cols, false);

// Mark the rows and columns that need to be updated
for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        if (mat[i][j] == 1) {
            rowMarker[i] = true;
            colMarker[j] = true;
        }
    }
}

// Update the matrix
for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        if (rowMarker[i] || colMarker[j]) {
            mat[i][j] = 1;
        }
    }
}

}

int main() { vector<vector> mat = { {1, 0, 0, 1}, {0, 0, 1, 0}, {0, 0, 0, 0} };

booleanMatrix(mat);
for (const vector<int>& row : mat) {
    for (int val : row) {
        cout << val << " ";
    }
    cout << endl;
}
return 0;

}

Java

// Java Code For Boolean Matrix Question // Using two extra arrays import java.util.*;

class GfG { static void booleanMatrix(int mat[][]) { int rows = mat.length; int cols = mat[0].length;

    // Arrays to keep track of rows and columns to be marked
    boolean[] rowMarker = new boolean[rows];
    boolean[] colMarker = new boolean[cols];

    // First pass: Mark the rows and columns to be updated
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (mat[i][j] == 1) {
                rowMarker[i] = true;
                colMarker[j] = true;
            }
        }
    }

    // Second pass: Update the matrix
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (rowMarker[i] || colMarker[j]) {
                mat[i][j] = 1;
            }
        }
    }
}

public static void main(String[] args) {
    int[][] arr = { 
        { 1, 0, 0, 1 },
        { 0, 0, 1, 0 },
        { 0, 0, 0, 0 } 
    };
    booleanMatrix(arr);
    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();
    }
}

}

Python

python3 Code For Boolean Matrix Question

Using two extra arrays

def booleanMatrix(mat): rows = len(mat) cols = len(mat[0])

# Arrays to keep track of rows and columns to be updated
rowMarker = [False] * rows
colMarker = [False] * cols

# First pass: Mark the rows and columns to be updated
for i in range(rows):
    for j in range(cols):
        if mat[i][j] == 1:
            rowMarker[i] = True
            colMarker[j] = True

# Second pass: Update the matrix
for i in range(rows):
    for j in range(cols):
        if rowMarker[i] or colMarker[j]:
            mat[i][j] = 1

if name == "main": arr = [[1, 0, 0, 1], [0, 0, 1, 0], [0, 0, 0, 0]] booleanMatrix(arr) for row in arr: print(" ".join(map(str, row)))

C#

// C# Code For Boolean Matrix Question // Using two extra arrays using System; using System.Collections.Generic;

class GfG { static void booleanMatrix(List<List> mat) { int rows = mat.Count; int cols = mat[0].Count;

    // Arrays to keep track of rows and columns to be updated
    bool[] rowMarker = new bool[rows];
    bool[] colMarker = new bool[cols];

    // First pass: Mark the rows and columns to be updated
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (mat[i][j] == 1) {
                rowMarker[i] = true;
                colMarker[j] = true;
            }
        }
    }

    // Second pass: Update the matrix
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (rowMarker[i] || colMarker[j]) {
                mat[i][j] = 1;
            }
        }
    }
}

// Test the BooleanMatrix function with a sample input
static void Main(string[] args) {
    List<List<int>> arr = new List<List<int>> {
        new List<int>{ 1, 0, 0, 1 },
        new List<int>{ 0, 0, 1, 0 },
        new List<int>{ 0, 0, 0, 0 }
    };

    booleanMatrix(arr);
    foreach (var row in arr) {
        Console.WriteLine(string.Join(" ", row));
    }
}

}

JavaScript

// Javascript Code For Boolean Matrix Question // Using two extra arrays function booleanMatrix(mat) {

const rows = mat.length;
const cols = mat[0].length;

// Arrays to keep track of rows and columns to be
// updated
const rowMarker = new Array(rows).fill(false);
const colMarker = new Array(cols).fill(false);

// First pass: Mark the rows and columns to be updated
for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
        if (mat[i][j] === 1) {
            rowMarker[i] = true;
            colMarker[j] = true;
        }
    }
}

// Second pass: Update the matrix
for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
        if (rowMarker[i] || colMarker[j]) {
            mat[i][j] = 1;
        }
    }
}

}

// Driver Code const arr = [ [ 1, 0, 0, 1 ], [ 0, 0, 1, 0 ], [ 0, 0, 0, 0 ] ]; booleanMatrix(arr); arr.forEach(row => console.log(row.join(" ")));

`

Output

1 1 1 1 1 1 1 1 1 0 1 1

**Time Complexity: O(n * m) where n is number of rows and m is number of columns in given matrix.
**Auxiliary Space: O(n + m) as we are taking two arrays one of size m and another of size n.

**[Expected Approach] Without Using Extra Space

Instead of taking two dummy arrays we can **use the first row and first 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. So we traverse in the reverse direction.
Since **matrix[0][0] are overlapping in first row and first column. 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.

C++ `

// C++ Code For Boolean Matrix Question // Most Optimised Approach #include #include using namespace std;

void booleanMatrix(vector<vector>& mat) { int col0 = 0, rows = mat.size(), cols = mat[0].size();

// Step 1: Mark the first row and 
// column if there is a 1 in the matrix
for (int i = 0; i < rows; i++) {
  
  // Check if 0th column contains 1
    if (mat[i][0] == 1) col0 = 1; 
    for (int j = 1; j < cols; j++) {
        if (mat[i][j] == 1) {
            mat[i][0] = 1;  
            mat[0][j] = 1;  
        }
    }
}

// Step 2: Traverse the matrix in 
// reverse direction and update values
for (int i = rows - 1; i >= 0; i--) {
    for (int j = cols - 1; j >= 1; j--) {
        if (mat[i][0] == 1 || mat[0][j] == 1) {
            mat[i][j] = 1;
        }
    }
    if (col0 == 1) {
        mat[i][0] = 1;
    }
}

}

int main() { vector<vector> arr = {{1, 0, 0, 1}, {0, 0, 1, 0}, {0, 0, 0, 0}};

booleanMatrix(arr);

for (int i = 0; i < arr.size(); i++) {
    for (int j = 0; j < arr[0].size(); j++) {
        cout << arr[i][j] << " ";
    }
    cout << endl;
}
return 0;

}

Java

// Java Code For Boolean Matrix Question // Most Optimised Approach import java.util.*;

class GfG {

static void booleanMatrix(int mat[][]) {
    int col0 = 0;
    int rows = mat.length, cols = mat[0].length;

    // Step 1: Mark the first row and 
    // column if there is a 1 in the matrix
    for (int i = 0; i < rows; i++) {
      
       // Check if 0th column contains 1
        if (mat[i][0] == 1) col0 = 1;
        for (int j = 1; j < cols; j++) {
            if (mat[i][j] == 1) {
                mat[i][0] = 1;  
                mat[0][j] = 1;  
            }
        }
    }

    // Step 2: Traverse the matrix in reverse
    // direction and update values
    for (int i = rows - 1; i >= 0; i--) {
        for (int j = cols - 1; j >= 1; j--) {
            if (mat[i][0] == 1 || mat[0][j] == 1) {
                mat[i][j] = 1;  
            }
        }
        if (col0 == 1) {
            mat[i][0] = 1;
        }
    }
}

public static void main(String[] args) {
    int[][] arr = {
        {1, 0, 0, 1},
        {0, 0, 1, 0},
        {0, 0, 0, 0}
    };
    
    booleanMatrix(arr);
    
    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();
    }
}

}

Python

python3 Code For Boolean Matrix Question

Most Optimised Approach

def booleanMatrix(mat): col0 = 0 rows = len(mat) cols = len(mat[0])

# Step 1: Mark the first row and column
# if there is a 1 in the matrix
for i in range(rows):
  
    # Check if 0th column contains 1
    if mat[i][0] == 1:
        col0 = 1  
    for j in range(1, cols):
        if mat[i][j] == 1:
            mat[i][0] = 1  
            mat[0][j] = 1  

# Step 2: Traverse the matrix in reverse
# direction and update values
for i in range(rows - 1, -1, -1):
    for j in range(cols - 1, 0, -1):
        if mat[i][0] == 1 or mat[0][j] == 1:
            mat[i][j] = 1  
    if col0 == 1:
        mat[i][0] = 1 

if name == "main": arr = [ [1, 0, 0, 1], [0, 0, 1, 0], [0, 0, 0, 0] ]

booleanMatrix(arr)

for row in arr:
    print(" ".join(map(str, row)))

C#

// C# Code For Boolean Matrix Question // Most Optimised Approach using System;

class GfG {

static void booleanMatrix(int[,] mat) {
    int col0 = 0, rows = mat.GetLength(0),
        cols = mat.GetLength(1);

    // Step 1: Mark the first row and column
    // if there is a 1 in the matrix
    for (int i = 0; i < rows; i++) {
      
      // Check if 0th column contains 1
        if (mat[i, 0] == 1) col0 = 1; 
        for (int j = 1; j < cols; j++) {
            if (mat[i, j] == 1) {
                mat[i, 0] = 1;  
                mat[0, j] = 1;  
            }
        }
    }

    // Step 2: Traverse the matrix in reverse
    // direction and update values
    for (int i = rows - 1; i >= 0; i--) {
        for (int j = cols - 1; j >= 1; j--) {
            if (mat[i, 0] == 1 || mat[0, j] == 1) {
                mat[i, j] = 1;  
            }
        }
        if (col0 == 1) {
            mat[i, 0] = 1;
        }
    }
}

static void Main() {
    int[,] arr = {
        {1, 0, 0, 1},
        {0, 0, 1, 0},
        {0, 0, 0, 0}
    };

    booleanMatrix(arr);

    for (int i = 0; i < arr.GetLength(0); i++) {
        for (int j = 0; j < arr.GetLength(1); j++) {
            Console.Write(arr[i, j] + " ");
        }
        Console.WriteLine();
    }
}

}

JavaScript

// Javascript Code For Boolean Matrix Question // Most Optimised Approach function booleanMatrix(mat) { let col0 = 0; const rows = mat.length; const cols = mat[0].length;

// Step 1: Mark the first row and column 
// if there is a 1 in the matrix
for (let i = 0; i < rows; i++) {
    // Check if 0th column contains 1
    if (mat[i][0] === 1) col0 = 1; 
    for (let j = 1; j < cols; j++) {
        if (mat[i][j] === 1) {
            mat[i][0] = 1;  
            mat[0][j] = 1;  
        }
    }
}

// Step 2: Traverse the matrix in reverse direction and update values
for (let i = rows - 1; i >= 0; i--) {
    for (let j = cols - 1; j >= 1; j--) {
        if (mat[i][0] === 1 || mat[0][j] === 1) {
            mat[i][j] = 1;
        }
    }
    if (col0 === 1) {
        mat[i][0] = 1;
    }
}

}

// Driver Code const arr = [ [1, 0, 0, 1], [0, 0, 1, 0], [0, 0, 0, 0] ];

booleanMatrix(arr);

for (let i = 0; i < arr.length; i++) { console.log(arr[i].join(" ")); }

`

Output

1 1 1 1 1 1 1 1 1 0 1 1

**Time Complexity: O(n * m) where n is number of rows and m is number of columns in given matrix.
**Auxiliary Space: O(1)