Amazon Interview Question | Java | 73. Set Matrix Zeroes
78
Apr 07, 2024
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.
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]

Constraints:
m == matrix.length
n == matrix[0].length
1 <= m, n <= 200
-231 <= matrix[i][j] <= 231 - 1
class Solution {
public void setZeroes(int[][] matrix) {
int n = matrix.length;
int m = matrix[0].length;
int[] row = new int[n]; // row array
int[] col = new int[m]; // col array
// Traverse the matrix:
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[i][j] == 0) {
// mark ith index of row wih 1:
row[i] = 1;
// mark jth index of col wih 1:
col[j] = 1;
}
}
}
// Finally, mark all (i, j) as 0
// if row[i] or col[j] is marked with 1.
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (row[i] == 1 || col[j] == 1) {
matrix[i][j] = 0;
}
}
}
}
}Comments (0)

