Set Matrix Zeroes leetcode

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

click to show follow up.

 

Subscribe to see which companies asked this question

方法:用矩阵中的某一零行来记录零列的信息

过程如下:

1.从下往上遍历矩阵,找到第一个0元素,我们将其所在行作为记录行,用它来记录列号

2.接着从上向下遍历矩阵,找到0元素,将其所在行赋值为0,并在记录行中同列的元素赋值为0,作为记录

3.根据记录行中的记录,将0元素所在的列全部赋值为0

4.将记录行赋值为0

void setZeroes(vector<vector<int>>& matrix) {
    const int h = matrix.size();
    const int w = matrix[0].size();
    int store = -1;
    for (int i = h - 1; i >= 0; --i)
    {
        if (store != -1)
            break;
        for (int j = 0; j < w; ++j)
        {
            if (matrix[i][j] == 0)
            {
                store = i;
                break;
            }
        }
    }
    if (store == -1)
        return;
    for (int i = 0; i < store; ++i)
    {
        bool isZero = false;
        for (int j = 0; j < w; ++j)
        {
            if (matrix[i][j] == 0)
            {
                matrix[store][j] = 0;
                isZero = true;
            }
        }
        if (isZero)
            for (int j = 0; j < w; ++j)
                matrix[i][j] = 0;
    }

    for (int j = 0; j < w; ++j)
        if(matrix[store][j] == 0)
            for (int i = 0; i < h; ++i)
                matrix[i][j] = 0;

    for (int j = 0; j < w; ++j)
        matrix[store][j] = 0;
}
原文地址:https://www.cnblogs.com/sdlwlxf/p/5134581.html