Set Matrix Zeroes

Source: Internet
Author: User

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?

1,o (mn), which uses a matrix of the same size to record 0 of that position.

2,o (m + n) is a row of columns to mark which row has 0.

3, constant space, that is, consider not using extra space, you can use the first row and the first column as the marker row and the tag column, but first determine whether the first row and the first column itself should be set to 0.

classSolution { Public:    voidSetzeroes (vector<vector<int>>&matrix) {       if(Matrix.size () <1)return; introw = Matrix.size (), col = matrix[0].size (); BOOLR0 =false, C0 =false;  for(inti =0; i < row; ++i) {if(matrix[i][0] ==0) {C0=true; Break; }         }          for(intj =0; J < Col; ++j) {if(matrix[0][J] = =0) {R0=true; Break; }         }          for(inti =1; i < row; ++i) { for(intj =1; J < Col; ++j) {matrix[i][0] = (Matrix[i][j] = =0) ?0: matrix[i][0]; matrix[0][J] = (matrix[i][j] = =0) ?0: matrix[0][j]; }            }          for(inti =1; i < row; ++i) { for(intj =1; J < Col; ++j) {Matrix[i][j]= (matrix[i][0] ==0) ?0: Matrix[i][j]; MATRIX[I][J]= (matrix[0][J] = =0) ?0: Matrix[i][j]; }            }          for(inti =0; I < row && C0; ++i) matrix[i][0] =0;  for(intj =0; J < Col && R0; ++J) matrix[0][J] =0; }};

Set Matrix Zeroes

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.