Leetcode 3033. Modify the Matrix
You are given an ( m \times n ) integer matrix. If a cell has the value 0
, you should set all the cells in its row and column to 0
. Implement a function to perform this operation without using extra space for another matrix.
[
[1, 2, 3],
[4, 0, 6],
[7, 8, 9]
]
[
[1, 0, 3],
[0, 0, 0],
[7, 0, 9]
]
0
. Use the first row and the first column of the matrix to store this information instead of using extra space.Here’s the Java code that performs the above-stated strategy:
public class Solution {
public void setZeroes(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return;
}
int rows = matrix.length;
int cols = matrix[0].length;
boolean firstRowZero = false;
boolean firstColZero = false;
// Checking if the first row needs to be zeroed
for (int j = 0; j < cols; j++) {
if (matrix[0][j] == 0) {
firstRowZero = true;
break;
}
}
// Checking if the first column needs to be zeroed
for (int i = 0; i < rows; i++) {
if (matrix[i][0] == 0) {
firstColZero = true;
break;
}
}
// Use first row and column to mark zeros
for (int i = 1; i < rows; i++) {
for (int j = 1; j < cols; j++) {
if (matrix[i][j] == 0) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
// Zero out cells based on the markers in the first row and column
for (int i = 1; i < rows; i++) {
for (int j = 1; j < cols; j++) {
if (matrix[i][0] == 0 || matrix[0][j] == 0) {
matrix[i][j] = 0;
}
}
}
// Zero out the first row if needed
if (firstRowZero) {
for (int j = 0; j < cols; j++) {
matrix[0][j] = 0;
}
}
// Zero out the first column if needed
if (firstColZero) {
for (int i = 0; i < rows; i++) {
matrix[i][0] = 0;
}
}
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?