Article Directory
1. Source of the subject
Link: 73. Matrix Zeroing
2. Topic analysis
For pure thinking questions, it is very good to use the best method to save the country.
Use the variables in the first row and the first column to indicate whether there is 0 in this column and row. In this way, it will be independent at the time of recovery.
- Time complexity : O (n 2) O(n^2)O ( n2)。
- Space complexity : O (1) O (1)O ( 1 )
Code:
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int n = matrix.size(), m = matrix[0].size();
if (!n || !m) return ;
int r0 = 1, c0 = 1;
for (int i = 0; i < m; i ++ ) if (!matrix[0][i]) r0 = 0;
for (int i = 0; i < n; i ++ ) if (!matrix[i][0]) c0 = 0;
for (int i = 1; i < m; i ++ )
for (int j = 1; j < n; j ++ )
if (!matrix[j][i])
matrix[0][i] = 0;
for (int i = 1; i < n; i ++ )
for (int j = 1; j < m; j ++ )
if (!matrix[i][j])
matrix[i][0] = 0;
for (int i = 1; i < n; i ++ )
if (!matrix[i][0])
for (int j = 1; j < m; j ++ )
matrix[i][j] = 0;
for (int i = 1; i < m; i ++ )
if (!matrix[0][i])
for (int j = 1; j < n; j ++ )
matrix[j][i] = 0;
if (!r0) for (int i = 0; i < m; i ++ ) matrix[0][i] = 0;
if (!c0) for (int i = 0; i < n; i ++ ) matrix[i][0] = 0;
}
};