← Home

73. Set Matrix Zeroes

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
straightforward implementationC++Markdown
73

This problem looks busy at first, but the accepted solution is built around one steady invariant. For 73. Set Matrix Zeroes, the solution in this repository is mainly a straightforward implementation solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: straightforward implementation.

The notes already sitting in the source point us in the right direction:

  • time: O(m*n), space: O(m+n)

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are setZeroes, rows.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Start from the smallest reliable state.
  2. Expand one legal move at a time.
  3. Cache, count, or merge information as soon as it becomes settled.
  4. Let the final stored value answer the original question.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(m*n), space: O(1)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 24 ms, faster than 92.32% of C++ online submissions for Set Matrix Zeroes.
02//Memory Usage: 13.5 MB, less than 15.07% of C++ online submissions for Set Matrix Zeroes.
03//time: O(m*n), space: O(m+n)
04class Solution {
05public:
06    void setZeroes(vector<vector<int>>& matrix) {
07        int m = matrix.size();
08        if(m == 0) return;
09        int n = matrix[0].size();
10        if(n == 0) return;
11        
12        vector<bool> rows(m, false), cols(n, false);
13        
14        for(int i = 0; i < m; ++i){
15            for(int j = 0; j < n; ++j){
16                if(matrix[i][j] == 0){
17                    rows[i] = true;
18                    cols[j] = true;
19                }
20            }
21        }
22        
23        for(int i = 0; i < m; ++i){
24            if(rows[i]){
25                for(int j = 0; j < n; ++j){
26                    matrix[i][j] = 0;
27                }
28            }
29        }
30        
31        for(int j = 0; j < n; ++j){
32            if(cols[j]){
33                for(int i = 0; i < m; ++i){
34                    matrix[i][j] = 0;
35                }
36            }
37        }
38    }
39};
40
41//Approach 2: O(1) Space, Efficient Solution
42//Runtime: 24 ms, faster than 92.32% of C++ online submissions for Set Matrix Zeroes.
43//Memory Usage: 13.6 MB, less than 9.84% of C++ online submissions for Set Matrix Zeroes.
44//time: O(m*n), space: O(1)
45class Solution {
46public:
47    void setZeroes(vector<vector<int>>& matrix) {
48        int m = matrix.size();
49        if(m == 0) return;
50        int n = matrix[0].size();
51        if(n == 0) return;
52        
53        /*
54        matrix[0][0] indicates the first row should be zero out,
55        so we need this variable whether first col should be zero out or not
56        */
57        bool firstCol = false;
58        
59        for(int i = 0; i < m; ++i){
60            //special case: first column
61            if(matrix[i][0] == 0){
62                firstCol = true;
63            }
64            
65            //for 2nd and later columns, we use the first row as indicator
66            for(int j = 1; j < n; ++j){
67                if(matrix[i][j] == 0){
68                    matrix[i][0] = matrix[0][j] = 0;
69                }
70            }
71        }
72        
73        /*
74        note that i starts from 1!
75        we zero out the part right and down to matrix[1][1](included) first
76        */
77        for(int i = 1; i < m; ++i){
78            if(matrix[i][0] == 0){
79                //j starts from 1
80                for(int j = 1; j < n; ++j){
81                    matrix[i][j] = 0;
82                }
83            }
84        }
85        
86        //j starts from 1
87        for(int j = 1; j < n; ++j){
88            if(matrix[0][j] == 0){
89                //i starts from 1
90                for(int i = 1; i < m; ++i){
91                    matrix[i][j] = 0;
92                }
93            }
94        }
95        
96        // for(int i = 0; i < m; ++i){
97        //     for(int j = 0; j < n; ++j){
98        //         cout << matrix[i][j] << " ";
99        //     }
100        //     cout << endl;
101        // }
102        // cout << "===================" << endl;
103        
104        /*
105        finally zero out the first row
106        */
107        if(matrix[0][0] == 0){
108            for(int j = 1; j < n; ++j){
109                matrix[0][j] = 0;
110            }
111        }
112        
113        // for(int i = 0; i < m; ++i){
114        //     for(int j = 0; j < n; ++j){
115        //         cout << matrix[i][j] << " ";
116        //     }
117        //     cout << endl;
118        // }
119        // cout << "===================" << endl;
120        
121        /*
122        finally zero out the first col
123        */
124        if(firstCol){
125            //i starts from 0
126            for(int i = 0; i < m; ++i){
127                matrix[i][0] = 0;
128            }
129        }
130        
131        // for(int i = 0; i < m; ++i){
132        //     for(int j = 0; j < n; ++j){
133        //         cout << matrix[i][j] << " ";
134        //     }
135        //     cout << endl;
136        // }
137        // cout << "===================" << endl;
138    }
139};

Cost

Complexity

Time
O(m*n), space: O(1)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.