利用第一行和第一列存储状态:

  • 首先记录第一行第一列中是否含有0
  • 遍历矩阵,如果元素为0,将对应的行头和列头的元素置0
  • 再次遍历矩阵,如果对应的行头或列头元素为0,将当前元素置0
  • 最后,如果第一行原来就有0,将第一行置0,第一列同样操作
//
// Created by jt on 2020/9/25.
//
#include <vector>
using namespace std;

class Solution {
public:
    void setZeroes(vector<vector<int> > &matrix) {
        bool firstRowHas0 = false, firstColHas0 = false;
        for (int i = 0; i < matrix.size(); ++i) {
            if (matrix[i][0] == 0) { firstColHas0 = true; break; }
        }
        for (int i = 0; i < matrix[0].size(); ++i) {
            if (matrix[0][i] == 0) { firstRowHas0 = true; break; }
        }
        for (int i = 0; i < matrix.size(); ++i) {
            for (int j = 0; j < matrix[0].size(); ++j) {
                if (matrix[i][j] == 0) {
                    matrix[0][j] = 0; matrix[i][0] = 0;
                }
            }
        }
        for (int i = 1; i < matrix.size(); ++i) {
            for (int j = 1; j < matrix[0].size(); ++j){
                if (matrix[0][j] == 0 || matrix[i][0] == 0) matrix[i][j] = 0;
            }
        }
        if (firstRowHas0) {
            for (int i = 0; i < matrix[0].size(); ++i) {
                matrix[0][i] = 0;
            }
        }
        if (firstColHas0) {
            for (int i = 0; i < matrix.size(); ++i) {
                matrix[i][0] = 0;
            }
        }
    }
};