首页 > 代码库 > Leetcode:Set Matrix Zeroes

Leetcode:Set Matrix Zeroes

戳我去解题

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

这题还是很简单的,就是有点坑,遍历矩阵的时候,每遇到0的时候,我们不能立即将所在行和列置0,否则,到最后矩阵所有值都为0了,

而应该将所在的行和列号存储起来,最后遍历完矩阵之后,再根据所存储的行列号来置0

class Solution {
public:
    void setZeroes(vector<vector<int> > &matrix) {
        int row = matrix.size();
        int col = matrix.at(0).size();
        set<int> rowZeros;  
        set<int> colZeros;
        for (int i = 0; i < row; ++i) {
            for (int j = 0; j < col; ++j) {
                if (matrix.at(i).at(j) == 0) {
                    rowZeros.insert(i);
                    colZeros.insert(j);
                }
            }
        }
        for (auto iter = rowZeros.begin(); iter != rowZeros.end(); ++iter) {
            fill(matrix.at(*iter).begin(), matrix.at(*iter).end(), 0);
        }
        for (auto iter = colZeros.begin(); iter != colZeros.end(); ++iter) {
            for (int j = 0; j < row; ++j) {
                matrix.at(j).at(*iter) = 0; 
            }
        }
    }
};