Given an m x n matrix (a grid) of integers, modify the matrix in-place such that all elements in any row or column that contains a zero are set to zero.
The approach involves three steps:
function setZeroes(matrix) {
let m = matrix.length;
if (m === 0) return;
let n = matrix[0].length;
// Arrays to mark which rows and columns need to be set to zero
let zeroesRow = new Array(m).fill(false);
let zeroesCol = new Array(n).fill(false);
// Step 1: Identify rows and columns containing zeros
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (matrix[i][j] === 0) {
zeroesRow[i] = true;
zeroesCol[j] = true;
}
}
}
// Step 2: Set the entire row or column to zero
for (let i = 0; i < m; i++) {
if (zeroesRow[i]) {
matrix[i].fill(0);
}
}
for (let j = 0; j < n; j++) {
if (zeroesCol[j]) {
// Ensure all elements in this column are set to zero
for (let i = 0; i < m; i++) {
matrix[i][j] = 0;
}
}
}
return matrix;
}
zeroesRow
and zeroesCol
, respectively.fill(0)
. We then iterate through each marked column and set each element in that
column to zero.O(m + n)
, where m
is the number of rows and n
is the number of columns.zeroesRow
and zeroesCol
) to keep track of which rows and columns need to be zeroed out.Consider a 3x3 matrix:
1 2 0
4 5 6
7 8 9
0 0 0
4 5 6
7 8 9
0 0 0
4 5 0
7 8 0
https://leetcode.com/problems/set-matrix-zeroes/
Loading component...
Loading component...
Main Function is not defined.
INPUT: [[1 2 0][ 4 5 6][ 7 8 9]]
OUTPUT: [[0 0 0][ 4 5 6 ][7 8 9]]
public static void setZeroes(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean firstRowZero = false;
boolean firstColZero = false;
for(int i =0; i < m; i++) {
if( matrix[i][0] == 0) {
firstColZero = true;
break;
}//If End
}//Loop End
for (int j = 0; j < n; j++) {
if (matrix[0][j] == 0) {
firstRowZero = true;
break;
}//If End
}//Loop End
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}//If End
}//Loop End
}//Loop End
for (int i = 1; i < m; i++) {
if (matrix[i][0] == 0) {
Arrays.fill(matrix[i], 0);
}//If End
}//Loop End
for (int j = 1; j < n; j++) {
if (matrix[0][j] == 0) {
for (int i = 0; i < m; i++) {
matrix[i][j] = 0;
}//Loop End
}//If End
}//Loop End
if (firstRowZero) {
Arrays.fill(matrix[0], 0);
}//If End
if (firstColZero) {
for (int i = 0; i < m; i++) {
matrix[i][0] = 0;
}//Loop End
}//If End
}//function end
Utility Function is not required.