[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列的状态。

原文地址:https://www.cnblogs.com/yanhewu/p/8460560.html