The Set Matrix zeroes? (Graph)

Source: Internet
Author: User

Given a m x n Matrix, if an element was 0, set its entire row and column to 0. Do it on place.

Follow up:

Did you use extra space?
A straight forward solution using O (mn) space is probably a bad idea.
A Simple Improvement uses O (m + n) space, but still is not the best solution.
Could you devise a constant space solution?

Idea: The first row and the first column are used to indicate the row, whether the column is full 0, but the first row, the first column whether full 0=> with two additional variables stored

classSolution { Public:    voidSetzeroes (vector<vector<int> > &matrix) {        if(Matrix.empty ())return; BOOLFirstlinezero =false; BOOLFirstcolumnzero =false; if(matrix[0][0]==0) {Firstlinezero=true; Firstcolumnzero=true; }        // the first line         for(inti =1; i<matrix[0].size (); i++)        {            if(matrix[0][i]!=0)Continue; Firstlinezero=true;  Break; }         //The first column         for(inti =1; I<matrix.size (); i++)        {            if(matrix[i][0]!=0)Continue; Firstcolumnzero=true;  Break; }                   for(inti =1; I < matrix.size (); i++)        {             for(intj =1; j<matrix[0].size (); J + +)            {                if(Matrix[i][j]! =0)Continue; matrix[i][0] =0; matrix[0][J] =0; }        }         for(inti =1; i<matrix[0].size (); i++)        {            if(matrix[0][i]!=0)Continue;  for(intj =1; J<matrix.size (); J + +) {Matrix[j][i]=0; }        }         for(inti =1; I<matrix.size (); i++)        {            if(matrix[i][0]!=0)Continue;  for(intj =1; j<matrix[0].size (); J + +) {Matrix[i][j]=0; }        }                if(Firstlinezero) { for(inti =0; i< matrix[0].size (); i++) {matrix[0][i] =0; }        }        if(Firstcolumnzero) { for(inti =0; i< matrix.size (); i++) {matrix[i][0] =0; }        }    }};

The Set Matrix zeroes? (Graph)

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.