[Leetcode] Set Matrix Zeroes

Posted 言何午

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode] Set Matrix Zeroes相关的知识,希望对你有一定的参考价值。

Set Matrix Zeroes 题解

题目来源:https://leetcode.com/problems/set-matrix-zeroes/description/


Description

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

Follow up:

Did you use extra space?

A straight forward solution using O(mn) space is probably a bad idea.

A simple improvement uses O(m + n) space, but still not the best solution.

Could you devise a constant space solution?

Solution

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        int row = matrix.size(), col = matrix[0].size();
        int i, j, col0 = 1;
        for (i = 0; i < row; i++) {
            if (matrix[i][0] == 0)
                col0 = 0;
            for (j = 1; j < col; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = matrix[0][j] = 0;
                }
            }
        }

        for (i = row - 1; i >= 0; i--) {
            for (j = col - 1; j >= 1; j--) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0)
                    matrix[i][j] = 0;
            }
            if (col0 == 0)
                matrix[i][0] = 0;
        }
    }
};

解题描述

这道题题意是,给出一个矩阵,对其中为0,将其所在的列和行全部置为零。而附加的条件是,要求解法只有常数空间复杂度。上面给出的解法思想在于,在矩阵第一列保存所有行的状态,在矩阵第一行保存所有列的状态,而matrix[0][0]位置会出现重叠,所以要多用一个变量col0来保存第0列的状态。

以上是关于[Leetcode] Set Matrix Zeroes的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-Set Matrix Zeroes

LeetCode -- Set Matrix Zeroes

Leetcode 73. Set Matrix Zeroes

LeetCode OJ 073Set Matrix Zeroes

LeetCode OJ 073Set Matrix Zeroes

LeetCode 73. Set Matrix Zeroes