Fork me on GitHub

Set Matrix Zeroes

Linkage

https://leetcode.com/problems/set-matrix-zeroes/description/

Solution

A traverse of will help us to mark which column or row should be marked as all zero. In this implementation, we will use O(m+n) space.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public void setZeroes(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
boolean[] row_index = new boolean[m];
boolean[] column_index = new boolean[n];
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
if (matrix[i][j] == 0) {
row_index[i] = true;
column_index[j] = true;
}
}
}
for (int i = 0; i < m; ++i){
if (row_index[i] == true){
for (int k = 0; k < n; k++){
matrix[i][k] = 0;
}
}
}

for (int j = 0; j < n; ++j) {
if (column_index[j] == true) {
for (int k = 0; k < m; ++k) {
matrix[k][j] = 0;
}
}
}

}
}