用矩形的第一行和第一列充当mask
代码:
1 void setZeroes(vector<vector<int> > &matrix) { 2 if (matrix.empty() || matrix[0].empty()) return; 3 4 bool firstRow = false; 5 bool firstCol = false; 6 int m = matrix.size(); 7 int n = matrix[0].size(); 8 9 for (int i = 0; i < m; i++) 10 if (matrix[i][0] == 0) { 11 firstCol = true; 12 break; 13 } 14 15 for (int j = 0; j < n; j++) 16 if (matrix[0][j] == 0) { 17 firstRow = true; 18 break; 19 } 20 21 for (int i = 0; i < m; i++) { 22 for (int j = 0; j < n; j++) { 23 if (matrix[i][j] == 0) { 24 matrix[i][0] = 0; 25 matrix[0][j] = 0; 26 } 27 } 28 } 29 30 for (int i = 1; i < m; i++) 31 if (matrix[i][0] == 0) 32 for (int j = 1; j < n; j++) 33 matrix[i][j] = 0; 34 35 for (int j = 1; j < n; j++) 36 if (matrix[0][j] == 0) 37 for (int i = 1; i < m; i++) 38 matrix[i][j] = 0; 39 40 if (firstCol) 41 for (int i = 0; i < m; i++) 42 matrix[i][0] = 0; 43 if (firstRow) 44 for (int j = 0; j < n; j++) 45 matrix[0][j] = 0; 46 }