-
Notifications
You must be signed in to change notification settings - Fork 0
Example: Zero Matrix
Roberto Fronteddu edited this page Jul 29, 2024
·
2 revisions
Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's.
You must do it in place.
To solve this problem in place, you can use the first row and first column of the matrix itself to store the zero flags for their respective rows and columns. Here's a step-by-step Java solution:
- Initialize flags: Use two boolean variables to track if the first row and the first column should be zeroed.
- Mark zeroes: Traverse the matrix to mark zeroes in the first row and first column.
- Set zeroes: Use the marks to set entire rows and columns to zero.
Zero the first row and column if needed: Finally, use the boolean variables to zero out the first row and first column if necessary.
public class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean firstRowZero = false;
boolean firstColZero = false;
// Check if the first row has any zeros
for (int j = 0; j < n; j++) {
if (matrix[0][j] == 0) {
firstRowZero = true;
break;
}
}
// Check if the first column has any zeros
for (int i = 0; i < m; i++) {
if (matrix[i][0] == 0) {
firstColZero = true;
break;
}
}
// Use the first row and first column to mark zeros
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;
}
}
}
// Set matrix cells to zero based on marks
for (int i = 1; i < m; i++) {
if (matrix[i][0] == 0) {
for (int j = 1; j < n; j++) {
matrix[i][j] = 0;
}
}
}
for (int j = 1; j < n; j++) {
if (matrix[0][j] == 0) {
for (int i = 1; i < m; i++) {
matrix[i][j] = 0;
}
}
}
// Zero out the first row if needed
if (firstRowZero) {
for (int j = 0; j < n; j++) {
matrix[0][j] = 0;
}
}
// Zero out the first column if needed
if (firstColZero) {
for (int i = 0; i < m; i++) {
matrix[i][0] = 0;
}
}
}
}