Set Matrix Rows and Columns to Zeroes
Last Updated :
20 Dec, 2024
Given a matrix mat[][] of size nxm, the task is to update the matrix such that if an element is zero, set its entire row and column to zeroes.
Examples:
Input: mat[][] = [[1, -1, 1],
[-1, 0, 1],
[1, -1, 1]]
Output: [[1, 0, 1],
[0, 0, 0],
[1, 0, 1]]
Explanation: mat[1][1] = 0, so all elements in row 1 and column 1 are updated to zeroes.
Input: mat[][] = [[0, 1, 2, 0],
[3, 4, 0, 2],
[1, 3, 1, 5]]
Output: [[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 3, 0, 0]]
Explanation: mat[0][0], mat[1][2] and mat[0][3] are 0s, so all elements in row 0, row 1, column 0, column 2 and column 3 are updated to zeroes.
[Naive Approach] Using Two Auxiliary Arrays - O(n*m) Time and O(n+m) Space
The idea is to maintain two additional arrays, say rows[] and cols[] to store the rows and columns which contains at least one element equal to 0. So, first traverse the entire matrix and for each mat[i][j] = 0, mark rows[i] = true and cols[j] = true. Now in the second traversal, for each cell (i, j), if either rows[i] or cols[j] is marked as true, update mat[i][j] = 0 else continue to the next cell.
Illustration:
C++
// C++ code to implement Set Matrix Zeroes using
// two auxiliary arrays
#include <iostream>
#include <vector>
using namespace std;
void setMatrixZeroes(vector<vector<int>> &mat) {
int n = mat.size(), m = mat[0].size();
// To store which rows and columns are
// supposed to mark with zeroes
vector<bool> rows(n, false), cols(m, false);
// Traverse the matrix to fill rows[] and cols[]
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// If the cell contains zero then mark
// its row and column as zero
if (mat[i][j] == 0) {
rows[i] = true;
cols[j] = true;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// Mark cell (i, j) with zero if either
// of rows[i] or cols[j] is true
if (rows[i] || cols[j])
mat[i][j] = 0;
}
}
}
int main() {
vector<vector<int> > mat = { { 0, 1, 2, 0 },
{ 3, 4, 0, 2 },
{ 1, 3, 1, 5 } };
setMatrixZeroes(mat);
for (int i = 0; i < mat.size(); i++) {
for (int j = 0; j < mat[0].size(); j++) {
cout << mat[i][j] << " ";
}
cout << endl;
}
return 0;
}
Java
// Java code to implement Set Matrix Zeroes using
// two auxiliary arrays
import java.util.*;
class GfG {
static void setMatrixZeroes(int[][] mat) {
int n = mat.length, m = mat[0].length;
// To store which rows and columns are
// supposed to mark with zeroes
boolean[] rows = new boolean[n];
boolean[] cols = new boolean[m];
// Traverse the matrix to fill rows[] and cols[]
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// If the cell contains zero then mark
// its row and column as zero
if (mat[i][j] == 0) {
rows[i] = true;
cols[j] = true;
}
}
}
// Set matrix elements to zero if they
// belong to a marked row or column
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// Mark cell (i, j) with zero if either
// of rows[i] or cols[j] is true
if (rows[i] || cols[j]) {
mat[i][j] = 0;
}
}
}
}
public static void main(String[] args) {
int[][] mat = {
{ 0, 1, 2, 0 },
{ 3, 4, 0, 2 },
{ 1, 3, 1, 5 }
};
setMatrixZeroes(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();
}
}
}
Python
# Python code to implement Set Matrix Zeroes using
# two auxiliary arrays
def setMatrixZeroes(mat):
n = len(mat)
m = len(mat[0])
# To store which rows and columns are
# supposed to mark with zeroes
rows = [False] * n
cols = [False] * m
# Traverse the matrix to fill rows[] and cols[]
for i in range(n):
for j in range(m):
# If the cell contains zero then mark
# its row and column as zero
if mat[i][j] == 0:
rows[i] = True
cols[j] = True
# Set matrix elements to zero if they
# belong to a marked row or column
for i in range(n):
for j in range(m):
# Mark cell (i, j) with zero if either
# of rows[i] or cols[j] is true
if rows[i] or cols[j]:
mat[i][j] = 0
if __name__ == "__main__":
mat = [
[0, 1, 2, 0],
[3, 4, 0, 2],
[1, 3, 1, 5]
]
setMatrixZeroes(mat)
for row in mat:
print(" ".join(map(str, row)))
C#
// C# code to implement Set Matrix Zeroes using
// two auxiliary arrays
using System;
using System.Collections.Generic;
class GfG {
static void SetMatrixZeroes(int[][] mat) {
int n = mat.Length, m = mat[0].Length;
// To store which rows and columns are
// supposed to mark with zeroes
bool[] rows = new bool[n];
bool[] cols = new bool[m];
// Traverse the matrix to fill rows[] and cols[]
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// If the cell contains zero then mark
// its row and column as zero
if (mat[i][j] == 0) {
rows[i] = true;
cols[j] = true;
}
}
}
// Mark cells with zero if either of
// rows[i] or cols[j] is true
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// Mark cell (i, j) with zero if either
// of rows[i] or cols[j] is true
if (rows[i] || cols[j])
mat[i][j] = 0;
}
}
}
static void Main(string[] args) {
int[][] mat = new int[][] {
new int[] { 0, 1, 2, 0 },
new int[] { 3, 4, 0, 2 },
new int[] { 1, 3, 1, 5 }
};
SetMatrixZeroes(mat);
for (int i = 0; i < mat.Length; i++) {
for (int j = 0; j < mat[0].Length; j++) {
Console.Write(mat[i][j] + " ");
}
Console.WriteLine();
}
}
}
JavaScript
// JavaScript code to implement Set Matrix Zeroes
// using two auxiliary arrays
function setMatrixZeroes(mat) {
const n = mat.length, m = mat[0].length;
// To store which rows and columns are
// supposed to mark with zeroes
const rows = new Array(n).fill(false);
const cols = new Array(m).fill(false);
// Traverse the matrix to fill rows[] and cols[]
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
// If the cell contains zero then mark
// its row and column as zero
if (mat[i][j] === 0) {
rows[i] = true;
cols[j] = true;
}
}
}
// Mark cells with zero if either of rows[i]
// or cols[j] is true
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
// Mark cell (i, j) with zero if either
// of rows[i] or cols[j] is true
if (rows[i] || cols[j]) {
mat[i][j] = 0;
}
}
}
}
// Driver Code
let mat = [
[0, 1, 2, 0],
[3, 4, 0, 2],
[1, 3, 1, 5]
];
setMatrixZeroes(mat);
for (let row of mat) {
console.log(row.join(" "));
}
Output0 0 0 0
0 0 0 0
0 3 0 0
[Expected Approach] Using First Row and Column - O(n*m) Time and O(1) Space
In the previous approach we took two arrays to store the row's and column's status. Now instead of two auxiliary arrays, we can use the first row and first column of mat[][] to store which row elements and column elements are to be marked as zeroes.
So if the first cell of a row is set to 0, then all cells of that row should be updated with 0. Similarly, if the first cell of a column is set to 0, then all cells of that column should be updated to 0. Since cell (0, 0) is first cell of the first row as well as the first column, so maintain another variable, say c0 to store the status of the first column and cell(0, 0) will store the status of the first row.
Step-by-step algorithm:
- Traverse the matrix, and for each cell (i, j) such that mat[i][j] = 0, mark mat[i][0] and mat[0][j] as 0. Note: If i = 0, mark mat[0][0] as 0 and if j = 0, mark c0 as 0.
- Again traverse the matrix from (1, 1) to (n-1, m-1), and set mat[i][j] = 0 if either mat[i][0] = 0 or mat[0][j] = 0.
- Finally, update the first row and first column:
- If arr[0][0] = 0, set all elements in first row to 0.
- If c0 = 0, set all elements in the first column to 0.
Illustration:
C++
// C++ code to implement Set Matrix Zeroes using
// first row and column
#include <iostream>
#include <vector>
using namespace std;
void setMatrixZeroes(vector<vector<int>> &mat) {
int n = mat.size(), m = mat[0].size();
int c0 = 1;
// Traverse the arr and mark first cell of
// each row and column
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (mat[i][j] == 0) {
// mark i-th row
mat[i][0] = 0;
// mark j-th column
if (j == 0)
c0 = 0;
else
mat[0][j] = 0;
}
}
}
// Traverse and mark the matrix from (1, 1)
// to (n - 1, m - 1)
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
// Check for col & row
if (mat[i][0] == 0 || mat[0][j] == 0) {
mat[i][j] = 0;
}
}
}
// Mark the first row
if (mat[0][0] == 0) {
for (int j = 0; j < m; j++)
mat[0][j] = 0;
}
// Mark the first column
if (c0 == 0) {
for (int i = 0; i < n; i++)
mat[i][0] = 0;
}
}
int main() {
vector<vector<int> > mat = { { 0, 1, 2, 0 },
{ 3, 4, 0, 2 },
{ 1, 3, 1, 5 } };
setMatrixZeroes(mat);
for (int i = 0; i < mat.size(); i++) {
for (int j = 0; j < mat[0].size(); j++) {
cout << mat[i][j] << " ";
}
cout << endl;
}
return 0;
}
Java
// Java code to implement Set Matrix Zeroes using
// first row and column
import java.util.*;
class GfG {
static void setMatrixZeroes(int[][] mat) {
int n = mat.length, m = mat[0].length;
int c0 = 1;
// Traverse the arr and mark first cell of each row and column
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (mat[i][j] == 0) {
// mark i-th row
mat[i][0] = 0;
// mark j-th column
if (j == 0)
c0 = 0;
else
mat[0][j] = 0;
}
}
}
// Traverse and mark the matrix from (1, 1) to (n - 1, m - 1)
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
// Check for col & row
if (mat[i][0] == 0 || mat[0][j] == 0) {
mat[i][j] = 0;
}
}
}
// Mark the first row
if (mat[0][0] == 0) {
for (int j = 0; j < m; j++)
mat[0][j] = 0;
}
// Mark the first column
if (c0 == 0) {
for (int i = 0; i < n; i++)
mat[i][0] = 0;
}
}
public static void main(String[] args) {
int[][] mat = { { 0, 1, 2, 0 },
{ 3, 4, 0, 2 },
{ 1, 3, 1, 5 } };
setMatrixZeroes(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();
}
}
}
Python
# Python code to implement Set Matrix Zeroes using
# first row and column
def setMatrixZeroes(mat):
n = len(mat)
m = len(mat[0])
c0 = 1
# Traverse the arr and mark first cell of each row and column
for i in range(n):
for j in range(m):
if mat[i][j] == 0:
# mark i-th row
mat[i][0] = 0
# mark j-th column
if j == 0:
c0 = 0
else:
mat[0][j] = 0
# Traverse and mark the matrix from (1, 1) to (n - 1, m - 1)
for i in range(1, n):
for j in range(1, m):
# Check for col & row
if mat[i][0] == 0 or mat[0][j] == 0:
mat[i][j] = 0
# Mark the first row
if mat[0][0] == 0:
for j in range(m):
mat[0][j] = 0
# Mark the first column
if c0 == 0:
for i in range(n):
mat[i][0] = 0
if __name__ == "__main__":
mat = [
[0, 1, 2, 0],
[3, 4, 0, 2],
[1, 3, 1, 5]
]
setMatrixZeroes(mat)
for row in mat:
print(" ".join(map(str, row)))
C#
// C# code to implement Set Matrix Zeroes using
// first row and column
using System;
class GfG {
static void setMatrixZeroes(int[][] mat) {
int n = mat.Length, m = mat[0].Length;
int c0 = 1;
// Traverse the arr and mark first cell
// of each row and column
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (mat[i][j] == 0) {
// mark i-th row
mat[i][0] = 0;
// mark j-th column
if (j == 0)
c0 = 0;
else
mat[0][j] = 0;
}
}
}
// Traverse and mark the matrix from
// (1, 1) to (n - 1, m - 1)
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
// Check for col & row
if (mat[i][0] == 0 || mat[0][j] == 0) {
mat[i][j] = 0;
}
}
}
// Mark the first row
if (mat[0][0] == 0) {
for (int j = 0; j < m; j++)
mat[0][j] = 0;
}
// Mark the first column
if (c0 == 0) {
for (int i = 0; i < n; i++)
mat[i][0] = 0;
}
}
static void Main() {
int[][] mat = {
new int[] { 0, 1, 2, 0 },
new int[] { 3, 4, 0, 2 },
new int[] { 1, 3, 1, 5 }
};
setMatrixZeroes(mat);
for (int i = 0; i < mat.Length; i++) {
for (int j = 0; j < mat[i].Length; j++) {
Console.Write(mat[i][j] + " ");
}
Console.WriteLine();
}
}
}
JavaScript
// JavaScript code to implement Set Matrix Zeroes
// using first row and column
function setMatrixZeroes(mat) {
const n = mat.length, m = mat[0].length;
let c0 = 1;
// Traverse the array and mark first cell of each row and column
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
if (mat[i][j] === 0) {
// mark i-th row
mat[i][0] = 0;
// mark j-th column
if (j === 0)
c0 = 0;
else
mat[0][j] = 0;
}
}
}
// Traverse and mark the matrix from (1, 1) to (n - 1, m - 1)
for (let i = 1; i < n; i++) {
for (let j = 1; j < m; j++) {
// Check for col & row
if (mat[i][0] === 0 || mat[0][j] === 0) {
mat[i][j] = 0;
}
}
}
// Mark the first row
if (mat[0][0] === 0) {
for (let j = 0; j < m; j++)
mat[0][j] = 0;
}
// Mark the first column
if (c0 === 0) {
for (let i = 0; i < n; i++)
mat[i][0] = 0;
}
}
// Driver Code
let mat = [
[0, 1, 2, 0],
[3, 4, 0, 2],
[1, 3, 1, 5]
];
setMatrixZeroes(mat);
for (let row of mat) {
console.log(row.join(" "));
}
Output0 0 0 0
0 0 0 0
0 3 0 0
Similar Reads
Remove all zero-rows and all zero-columns from a Matrix
Given a matrix arr[][] of size N * M, the task is to print the matrix after removing all rows and columns from the matrix which consists of 0s only. Examples: Input: arr[][] ={ { 1, 1, 0, 1 }, { 0, 0, 0, 0 }, { 1, 1, 0, 1}, { 0, 1, 0, 1 } } Output: 111 111 011 Explanation: Initially, the matrix is a
15+ min read
Find Matrix With Given Row and Column Sums
Given two arrays rowSum[] and colSum[] of size n and m respectively, the task is to construct a matrix of dimensions n à m such that the sum of matrix elements in every ith row is rowSum[i] and the sum of matrix elements in every jth column is colSum[j].Note: The resultant matrix can have only non-n
15 min read
Making Row and Column Sums Equal
Given a square matrix of size n x n, the task is to find minimum number of operations that are required such that the sum of elements on each row and column becomes equal. In one operation, we can increment any value at any cell of the matrix by 1.Examples: Input: mat[][] = [[1, 2], [3, 4]]Output: 4
6 min read
Find Column with Maximum Zeros in Matrix
Given a matrix(2D array) M of size N*N consisting of 0s and 1s only. The task is to find the column with the maximum number of 0s. If more than one column exists, print the one which comes first. If the maximum number of 0s is 0 then return -1. Examples: Input: N = 3, M[][] = {{0, 0, 0}, {1, 0, 1},
5 min read
Print index of columns sorted by count of zeroes in the Given Matrix
Given a matrix with N rows and M columns. The task is to print the index of columns of the given matrix based on the increasing number of zeroes in each column. For Example, If the 1st column contains 2 zero's, the 2nd column contains 1 zero, and 3rd column does not contain any zeroes. Then the outp
8 min read
Counting sets of 1s and 0s in a binary matrix
Given n à m binary matrix, count the number of sets where a set can be formed one or more same values in a row or column. Examples: Input: 1 0 1 0 1 0 Output: 8 Explanation: There are six one-element sets (three 1s and three 0s). There are two two- element sets, the first one consists of the first a
7 min read
Find if a binary matrix exists with given row and column sums
Given an array Row[] of size R where Row[i] is the sum of elements of the ith row and another array Column[] of size C where Column[i] is the sum of elements of the ith column. The task is to check if it is possible to construct a binary matrix of R * C dimension which satisfies given row sums and c
7 min read
Count number of free cell present in the Matrix
Given a Matrix size N*N and an integer K. Initially, the matrix contains only 0. You are given K tasks and for each task, you are given two coordinates (r, c). Where coordinates (r, c) denotes the rth row and the cth column of the given matrix. You have to perform each task sequentially in the given
11 min read
A Boolean Matrix Question
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 ith row and jth 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
15+ min read
Find the original matrix from the given AND matrix
Given a binary matrix B[][] of size N*M, the task is to find a matrix A[][] of the same size such that B[i][j] is the bitwise AND of all the elements in ith row and jth column of A[][]. Examples: Input: B[][] = { {1, 0, 1}, {0, 0, 0} }Output: { {1, 1, 1}, {1, 0, 1} }Explanation:1 1 1 ? 1 0 11 0 1 0
10 min read