Leetcode Set Matrix Zeroes

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.

Click to show follow up.

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?

Test instructions: Set the row of 0 to 0.

Idea: In order not to open extra space, we use the first row and the first column, and then determine whether the first row, column also to set 0

Class Solution {Public:void setzeroes (vector<vector<int> > &matrix) {int n = matrix.size (); int m = Matrix [0].size (); bool FirstRow = false, Firstcol = false;for (int i = 0; i < n; i++) if (matrix[i][0] = = 0) {Firstcol = true; break;} for (int i = 0; i < m; i++) if (matrix[0][i] = = 0) {firstrow = True;break;} for (int i = 1, i < n; i++) {for (int j = 1; j < M; J + +) {if (matrix[i][j] = = 0) {Matrix[i][0] = 0;matrix[0][j] = 0; }}}for (int i = 1; i < n; i++) {if (matrix[i][0] = = 0) for (int j = 1; j < M; j + +) Matrix[i][j] = 0;} for (int i = 1, i < m; i++) {if (matrix[0][i] = = 0) for (int j = 1; j < N; j + +) Matrix[j][i] = 0;} if (firstrow) {for (int i = 0; i < m; i++) matrix[0][i] = 0;} if (Firstcol) {for (int i = 0; i < n; i++) matrix[i][0] = 0;}};


Leetcode 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.