Leetcode first fl_ _ Set Matrix Zeroes

Source: Internet
Author: User

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
  
   

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.