1. 程式人生 > >[Leetcode] Set Matrix Zeroes

[Leetcode] Set Matrix Zeroes

cnblogs follow lee 重疊 improve des gpo pac entire

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