零矩阵

题目

编写一种算法,若M × N矩阵中某个元素为0,则将其所在的行与列清零。

分析

两次遍历。第一次记录所有0的行、列,第二次遍历记录的行、列置0.

代码

class Solution {
    
    
public:
    void setZeroes(vector<vector<int>>& matrix) {
    
    
        int mRow = matrix.size();
        int mCol = matrix[0].size();
        if (mRow == 0 || mCol == 0) {
    
    
            return;
        }
        vector<bool> row(mRow, false);
        vector<bool> col(mCol, false);
        for (int i = 0; i < mRow; i++) {
    
    
            for (int j = 0; j < mCol; j++) {
    
    
                if (matrix[i][j] == 0) {
    
    
                    row[i] = true;
                    col[j] = true;
                }
            }
        }
        for (int i = 0; i < mRow; i++) {
    
    
            for (int j = 0; j < mCol; j++) {
    
    
                if (row[i] || col[j]) {
    
    
                    matrix[i][j] = 0;
                }
            }
        }
        return;
    }
};

知识积累

vector初始化,固定个数相同元素的方法:
vector<元素类型> 名字(个数,每个元素的值);

vector<bool> row(mRow, false);
vector<bool> col(mCol, false);
vector<int> myVector(10, 6); // 10个6的vector,名字叫myVector

猜你喜欢

转载自blog.csdn.net/weixin_36389889/article/details/112854411