classSolution { public: voidsetZeroes(vector<vector<int>> &matrix){ if (matrix.empty()) { return; } int m = matrix.size(); int n = matrix[0].size(); bool firstRowZeroFlag = false; bool firstColumnZeroFlag = false; for (int i = 0; i < m; ++i) { if (matrix[i][0] == 0) { firstColumnZeroFlag = true; } } for (int j = 0; j < n; ++j) { if (matrix[0][j] == 0) { firstRowZeroFlag = true; } }
for (int i = 1; i < m; ++i) { for (int j = 1; j < n; ++j) { // i,j从1开始,标签行和标签列先不动 if (matrix[i][j] == 0) { matrix[i][0] = matrix[0][j] = 0; } } } for (int i = 1; i < m; ++i) { for (int j = 1; j < n; ++j) { if (matrix[i][0] == 0 || matrix[0][j] == 0) { matrix[i][j] = 0; } } }
if (firstColumnZeroFlag) { for (int i = 0; i < m; ++i) { matrix[i][0]=0; } } if (firstRowZeroFlag) { for (int j = 0; j < n; ++j) { matrix[0][j]=0; } } } };