[LeetCode] Set Matrix Zeroes

73. Set Matrix Zeroes

Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0’s, and return the matrix.

You must do it in place.

  • Time : O(nm)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int n = matrix.size(), m = matrix[0].size();
bool zeroCol0 = false;
for(int i = 0; i < n; i++) {
zeroCol0 |= !matrix[i][0];
for(int j = 1; j < m; j++)
if(!matrix[i][j])
matrix[i][0] = matrix[0][j] = 0;
}
for(int i = n - 1; i >= 0; i--) {
for(int j = m - 1; j >= 1; j--) {
if(!matrix[i][0] || !matrix[0][j]) matrix[i][j] = 0;
}
}
if(zeroCol0) {
for(int i = 0; i < n; i++)
matrix[i][0] = 0;
}
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/07/PS/LeetCode/set-matrix-zeroes/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.