1、将找到的第一个0所在行列作为标记行列。
void setZeroes(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
int first_m = -1, first_n = -1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0 && first_m == -1 && first_n == -1) {
first_m = i; first_n = j;
for (int s = 0; s < m; s++) {
if (matrix[s][first_n] != 0)
matrix[s][first_n] = 1;
}
for (int t = 0; t < n; t++)
if (matrix[first_m][t] != 0)
matrix[first_m][t] = 1;
}
else if (matrix[i][j] == 0) {
matrix[first_m][j] = 0;
matrix[i][first_n] = 0;
}
}
}
if (first_m == -1)
return;
for (int i = 0; i < m; i++) {
if (i != first_m && matrix[i][first_n] == 0) {
for (int j = 0; j < n; j++) {
if (j != first_n) {
matrix[i][j] = 0;
}
}
}
}
for (int j = 0; j < n; j++) {
if (j != first_n && matrix[first_m][j] == 0) {
for (int i = 0; i < m; i++) {
if (i != first_m) {
matrix[i][j] = 0;
}
}
}
}
for (int i = 0; i < m; i++) {
matrix[i][first_n] = 0;
}
for (int j = 0; j < n; j++) {
matrix[first_m][j] = 0;
}
}
2、官方题解直接将第一行第一列作为标记行列,然后额外两个变量记录matrix[0][0]是否为0。后面遇0则修改第一行或第一列的值。