# [LeetCode 73. Set Matrix Zeroes ](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/614/week-2-august-8th-august-14th/3888/) ### Daily challenge Aug 13, 2021 (MEDIAN) >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**. ![](https://i.imgur.com/s6CGLhD.png) :::info **Example 1:** **Input:** matrix = [[1,1,1],[1,0,1],[1,1,1]] **Output:** [[1,0,1],[0,0,0],[1,0,1]] ::: ![](https://i.imgur.com/kJ6nGt0.png) :::info **Example 2:** **Input:** matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]] **Output:** [[0,0,0,0],[0,4,5,0],[0,3,1,0]] ::: :::warning **Constraints:** * m == matrix.length * n == matrix[0].length * 1 <= m, n <= 200 * -231 <= matrix[i][j] <= 231 - 1 ::: --- ### Approach 1 : :bulb: **`12 ms ( 82.05% )`** **`O()`** :::warning 此題題目要求需要使用 **`in-place`** 也就是直接使用 `matrix` 修改。 ::: * 因為要使用原本的 `matrix` 來做修改,並不能在遇到 `0` 之後直接讓該 `row、col` 都變為 `0`。 * 所以我們另外宣告兩個 `vector<bool>` 紀錄 `row、col` 是否有 `0` 出現。 * 最後再遍歷一次 `matrix`,並根據剛剛的紀錄判斷是否要設為 `0`。 > **`if(rows[i] || cols[j]) matrix[i][j] = 0`** ```cpp=1 class Solution { public: void setZeroes(vector<vector<int>>& matrix) { int m = matrix.size(); int n = matrix[0].size(); vector<bool> rows(m, false); vector<bool> cols(n, false); for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(matrix[i][j] == 0){ rows[i] = true; cols[j] = true; } } } for(int i=0; i<m; i++){ for(int j=0; j<n; j++){ if(rows[i] || cols[j]) matrix[i][j] = 0; } } } }; ```