1. 程式人生 > 其它 >[LeetCode] 73. Set Matrix Zeroes

[LeetCode] 73. Set Matrix Zeroes

[LeetCode] 73. Set Matrix Zeroes

題目

Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's, and return the matrix.

You must do it in place.

Example 1:

Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]

思路

可以開兩個陣列分別標記這一行/列是否有0。空間複雜度 O(n+m)

這兩個陣列可以用原矩陣的第一行第一列代替,但同時要判斷第一行第一列原來是否有0。

其實可以只用一個變數來判斷,待填坑。

程式碼

class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        int flag_col0 = false;
        for (int i = 0; i < m; i++) {
            if (!matrix[i][0]) {
                flag_col0 = true;
            }
            for (int j = 1; j < n; j++) {
                if (!matrix[i][j]) {
                    matrix[i][0] = matrix[0][j] = 0;
                }
            }
        }
        for (int i = m-1; i >= 0; i--) {
            for (int j = 1; j < n; j++) {
                if (!matrix[i][0] || !matrix[0][j]) {
                    matrix[i][j] = 0;
                }
            }
            if (flag_col0) matrix[i][0] = 0;
        }

    }
};
歡迎轉載,轉載請註明出處!