The Wayback Machine - https://web.archive.org/web/20240930190903/https://www.geeksforgeeks.org/a-boolean-matrix-question/
Open In App

A Boolean Matrix Question

Last Updated : 22 Aug, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Medium
40.05%
1.2L

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. 



Previous Article
Next Article

Similar Reads

Python | Print unique rows in a given boolean matrix using Set with tuples
Given a binary matrix, print all unique rows of the given matrix. Order of row printing doesn't matter. Examples: Input: mat = [[0, 1, 0, 0, 1], [1, 0, 1, 1, 0], [0, 1, 0, 0, 1], [1, 1, 1, 0, 0]] Output: (1, 1, 1, 0, 0) (0, 1, 0, 0, 1) (1, 0, 1, 1, 0) We have existing solution for this problem please refer link. We can solve this problem in python
2 min read
Find regions with most common region size in a given boolean matrix
Given a boolean 2D array, arr[][] of size N*M where a group of connected 1s forms an island. Two cells are said to be connected if they are adjacent to each other horizontally, vertically, or diagonally. The task is to find the position of the top left corner of all the regions with the most common region size. Examples: Input: arr[][] = {{0, 0, 1,
12 min read
Given a Boolean Matrix, find k such that all elements in k'th row are 0 and k'th column are 1.
Given a square boolean matrix mat[n][n], find k such that all elements in k'th row are 0 and all elements in k'th column are 1. The value of mat[k][k] can be anything (either 0 or 1). If no such k exists, return -1. Examples: Input: bool mat[n][n] = { {1, 0, 0, 0}, {1, 1, 1, 0}, {1, 1, 0, 0}, {1, 1, 1, 0}, }; Output: 0 All elements in 0'th row are
15 min read
Max Area of Island - Largest in Boolean Matrix
Given a binary 2D matrix, find area of the largest region of 1s which are connected horizontally, vertically or diagonally. Examples: Input: M[][]= {{1, 0, 0, 0, 1, 0, 0}, {0, 1, 0, 0, 1, 1, 0}, {1, 1, 0, 0, 0, 0, 0}, {1, 0, 0, 1, 1, 0, 0}, {1, 0, 0, 1, 0, 1, 1}} Output: 6Explanation: The region in red has the largest area of 6 cells. Input: M[][]
15+ min read
Generate matrix from given Sparse Matrix using Linked List and reconstruct the Sparse Matrix
Given a sparse matrix mat[][] of dimensions N*M, the task is to construct and represent the original matrix using a Linked List and reconstruct the givensparse matrix. Examples: Input: mat[][] = {{0, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 2, 0, 0}, {0, 3, 0, 0, 4}, {0, 0, 5, 0, 0}}Output:Linked list representation: (4, 2, 5) ? (3, 4, 4) ? (3, 1, 3) ?
15+ min read
Generate a Matrix such that given Matrix elements are equal to Bitwise OR of all corresponding row and column elements of generated Matrix
Given a matrix B[][] of dimensions N * M, the task is to generate a matrix A[][] of same dimensions that can be formed such that for any element B[i][j] is equal to Bitwise OR of all elements in the ith row and jth column of A[][]. If no such matrix exists, print "Not Possible". Otherwise, print the matrix A[][]. Examples: Input: B[][] = {{1, 1, 1}
11 min read
Minimum number of basic logic gates required to realize given Boolean expression
Given a string S of length N representing a boolean expression, the task is to find the minimum number of AND, OR, and NOT gates required to realize the given expression. Examples: Input: S = "A+B.C"Output: 2Explanation: Realizing the expression requires 1 AND gate represented by '.' and 1 OR gate represented by '+'. Input: S = "(1 - A). B+C"Output
4 min read
Problem solving on Boolean Model and Vector Space Model
Boolean Model: It is a simple retrieval model based on set theory and boolean algebra. Queries are designed as boolean expressions which have precise semantics. Retrieval strategy is based on binary decision criterion. Boolean model considers that index terms are present or absent in a document. Problem Solving: Consider 5 documents with a vocabula
4 min read
What is Boolean Expression
In this article, we will see what is Boolean Expression. Before starting with the topic directly lets us see what is a Boolean expression. It is an expression that always yields two values either true or false when evaluated. If the condition is true then it will return true or false and vice versa. Let's take one simple example that will clear the
4 min read
A Boolean Array Puzzle
Input: A array arr[] of two elements having value 0 and 1Output: Make both elements 0. Specifications: Following are the specifications to follow. 1) It is guaranteed that one element is 0 but we do not know its position.2) We can't say about another element it can be 0 or 1.3) We can only complement array elements, no other operation like and, or,
4 min read
Bit Manipulation technique to replace boolean arrays of fixed size less than 64
Space complexity is the most underestimated asset by programmers. One can barely see a Memory Limit Exceed (MLE) while submitting a solution. But, saving memory is the most important thing a programmer should take care about. If one needs to create an Application for a user, it should be made as memory efficient as one can. Boolean arrays have been
10 min read
Boolean Parenthesization Problem | DP-37
Given a boolean expression with the following symbols. Symbols 'T' ---> true 'F' ---> false And following operators filled between symbols Operators & ---> boolean AND | ---> boolean OR ^ ---> boolean XOR Count the number of ways we can parenthesize the expression so that the value of expression evaluates to true. Let the input b
15+ min read
Evaluate a boolean expression represented as string
Given a string consisting of only 0, 1, A, B, C where A = AND B = OR C = XOR Calculate the value of the string assuming no order of precedence and evaluation is done from left to right.Constraints – The length of string will be odd. It will always be a valid string. Example, 1AA0 will not be given as an input. Examples: Input : 1A0B1 Output : 1 1 A
7 min read
Check if it is possible to make the given matrix increasing matrix or not
Given a matrix of N X M of positive integers, the task is to find out whether it is possible to make the matrix increasing or not. Print the matrix constructed otherwise print -1. Matrix elements should be greater than zero. A matrix is said to be increasing matrix if: For each row, the elements are in the increasing order.For each column, the elem
10 min read
Program to check if a matrix is Binary matrix or not
Given a matrix, the task is to check if that matrix is a Binary Matrix. A Binary Matrix is a matrix in which all the elements are either 0 or 1. It is also called Logical Matrix, Boolean Matrix, Relation Matrix. Examples: Input: {{1, 0, 1, 1}, {0, 1, 0, 1} {1, 1, 1, 0}} Output: Yes Input: {{1, 0, 1, 1}, {1, 2, 0, 1}, {0, 0, 1, 1}} Output: No Approa
5 min read
Program to convert given Matrix to a Diagonal Matrix
Given a N*N matrix. The task is to convert the matrix to a diagonal matrix. That is to change the values of the non-diagonal elements of a matrix to 0.Diagonal-Matrix: A matrix is called a Diagonal Matrix if all the non-diagonal elements of the matrix are zero.Examples: Input : mat[][] = {{ 2, 1, 7 }, { 3, 7, 2 }, { 5, 4, 9 }} Output : {{2, 0, 7},
8 min read
Check if matrix can be converted to another matrix by transposing square sub-matrices
Given two N X M matrices of integers. In an operation, we can transpose any square sub-matrix in matrix1. The task is to check if matrix1 can be converted to matrix2 with the given operation.Examples: Input: matrix1[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, matrix2[][] = { {1, 4, 7}, {2, 5, 6}, {3, 8, 9}} Output: Yes Transpose the whole matrix and
10 min read
Minimum swaps needed to convert given Binary Matrix A to Binary Matrix B
Given two binary matrices, A[][] and B[][] of size N×M, the task is to find the minimum number of swaps of the elements of matrix A, needed to convert matrix A into matrix B. If it is impossible to do so then print "-1". Examples : Input: A[][] = {{1, 1, 0}, {0, 0, 1}, {0, 1, 0}}, B[][] = {{0, 0, 1}, {0, 1, 0}, {1, 1, 0}}Output: 3Explanation: One p
8 min read
Minimum number of steps to convert a given matrix into Upper Hessenberg matrix
Given a matrix of order NxN, Find the minimum number of steps to convert the given matrix into the Upper Hessenberg matrix. In each step, the only operation allowed is to decrease or increase any element value by 1.Examples: Input : N=3 1 2 8 1 3 4 2 3 4 Output :2 Decrease the element a[2][0] 2 times. Now the matrix is upper hessenbergInput : N=4 1
4 min read
Minimum steps required to convert the matrix into lower hessenberg matrix
Given a matrix of order NxN, Find the minimum number of steps to convert given matrix into Lower Hessenberg matrix. In each step, the only operation allowed is to decrease or increase any element value by 1.Examples: Input: mat[][] = { {1, 2, 8}, {1, 3, 4}, {2, 3, 4}} Output: 8 Decrease the element a[0][2] 8 times. Now the matrix is lower Hessenber
4 min read
Minimum number of steps to convert a given matrix into Diagonally Dominant Matrix
Given a matrix of order NxN, the task is to find the minimum number of steps to convert given matrix into Diagonally Dominant Matrix. In each step, the only operation allowed is to decrease or increase any element by 1.Examples: Input: mat[][] = {{3, 2, 4}, {1, 4, 4}, {2, 3, 4}} Output: 5 Sum of the absolute values of elements of row 1 except the d
6 min read
Maximize Matrix sum by replacing 0s such that Matrix remains sorted
Given a matrix mat[][] of dimension N*M which is sorted row-wise and column-wise, the task is to find the sum of the elements of the matrix by replacing all 0s in the matrix with any value such that the matrix remains sorted row-wise and column-wise. If it is not possible, then print "-1". Note: 0s will be only present in internal cells. i.e., neit
7 min read
Check if a given matrix can be converted to another given matrix by row and column exchanges
Given a matrix startMatrix and another matrix finalMatrix, the task is to check if startMatrix can be converted to finalMatrix by column exchanges and a row exchanges. Examples: Input: start[][] = {{1, 2, 3, 4}, {5, 6, 7, 8} {9, 10, 11, 12}, {13, 14, 15, 16}}final[][] = {{1, 4, 3, 2}, {5, 8, 7, 6}, {13, 16, 15, 14}, {9, 12, 11, 10}} Output: Yes Exp
9 min read
Create matrix whose sum of diagonals in each sub matrix is even
Given a number N, the task is to create a square matrix of size N*N with values in range [1, N*N], such that the sum of each diagonal of an even sub-square matrix is even. Examples: Input: N = 3Output: 1 2 3 4 5 6 7 8 9 Explanation:For each even sub-square matrix the sum of each diagonal is a even number.1 2 4 5 sum of each diagonal is 6 and 6 i.e
5 min read
Construct a square Matrix whose parity of diagonal sum is same as size of matrix
Given an integer N representing the size of the matrix, the task is to construct a square matrix N * N which have an element from 1 to N2 such that the parity of the sum of its diagonals is equal to the parity of integer N. Examples: Input: N = 4Output:1 2 3 4 8 7 6 59 10 11 1216 15 14 13Explanation:Sum of diagonal = 32 and 36 and integer N = 4, al
6 min read
Minimize count of adjacent row swaps to convert given Matrix to a Lower Triangular Matrix
Given a matrix, mat[][] of size N × N, the task is to minimize the count of adjacent row swaps to convert the given matrix to a lower triangular matrix. If it is not possible to convert the given matrix to a lower triangular matrix, then print -1. Note: A lower triangular matrix contains 0s at all the indices above the main diagonal. Examples: Inpu
9 min read
Count right angled triangles in a matrix having two of its sides parallel to sides of the matrix
Given a binary matrix arr[][] of dimensions N * M , the task is to count the number of right-angled triangles that can be formed by joining the cells containing the value 1 such that the triangles must have any two of its sides parallel to the sides of the rectangle. Examples: Input: arr[][] = {{0, 1, 0}, {1, 1, 1}, {0, 1, 0}}Output: 4Explanation:
8 min read
Construct a Matrix such that each cell consists of sum of adjacent elements of respective cells in given Matrix
Given a matrix arr[][] of dimensions N * M, the task is to generate a matrix such that any cell (r, c) stores the sum of adjacent elements present horizontally, vertically, and diagonally in the given matrix. Examples: Input: arr[][] = {{1, 3}, {2, 4}}Output: {{9, 7}, {8, 6}}Explanation: Matrix is constructed by the following operations: For cell (
9 min read
Print Matrix after multiplying Matrix elements N times
Given a square matrix mat[][] and an integer N, the task is to print the matrix after multiplying the matrix N times. Examples: Input: mat[][] = {{1, 2, 3}, {3, 4, 5}, {6, 7, 9}}, N = 2Output:25 31 4045 57 7481 103 134 Input: mat[][] = {{1, 2}, {3, 4}}, N = 3Output:37 5481 118 Approach: The idea is to use the Matrix Multiplication identity matrix.
9 min read
Convert a Matrix into another Matrix of given dimensions
Given a matrix, mat[][] of size N * M and two positive integers A and B, the task is to construct a matrix of size A * B from the given matrix elements. If multiple solutions exist, then print any one of them. Otherwise, print -1. Input: mat[][] = { { 1, 2, 3, 4, 5, 6 } }, A = 2, B = 3 Output: { { 1, 2, 3 }, { 4, 5, 6 } } Explanation: Since the siz
6 min read