At first glance, this question is very simple. In fact, it is quite skillful. My first thought was to find a special value mark. When I encountered a value of 0, we marked the non-zero element in the corresponding row and column as this special value, and the value of 0 remained unchanged, and then traverse it from the beginning, and convert it to 0 when it encounters a special value.
The problem is how to determine this special value. The value range is not given in the question. With luck, I used the largest and smallest int, which were all written out .. If you find a value that does not exist in the array, the complexity is too high.
Is there any better way? Of course. This idea is clever. The final result is to convert all the rows and columns where 0 are located into 0. In other words, to convert 0, you only need to mark the row and column, can you find a way to mark this task? If a scan reaches 0, we will set the first value in the row and column of this number to 0 for marking. After all the scans are completed, set it to 0 for the rows with the first and first columns as 0.
There is a detail. What should I do for the first row and the first column? They may not be 0 at the beginning, because there are 0 reasons for marking. How can we distinguish between them? The processing method is actually very simple. First, let's take a look at whether it contains 0, and then decide whether to convert them to 0 based on the result.
class Solution {public: void setZeroes(vector
> &matrix) { int row = matrix.size(), column = matrix[0].size(); bool firstRow = false, firstColumn = false; for(int i=0;i