Leetcode Detail Implementation Set Matrix zeroes

Source: Internet
Author: User

Set Matrix ZeroesTotal Accepted: 18139 Total Submissions: 58671 My Submissions

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.



Test instructions: Given a matrix, assume that a position of the matrix is 0. Set the entire element of that row to 0.
Idea: Use two bool arrays to record rows and columns where all elements should be set to 0
Complexity: Time O (m*n). Space O (m+n)


void Setzeroes (Vector<vector<int> > &matrix) {if (Matrix.empty ()) return; int rows = Matrix.size (), columns = matrix[0].size ();vector<bool> row (rows, False);vector<bool> column (columns, false); for (int i = 0; i < rows; ++i) {for (int j = 0; j < columns; ++j) {if (matrix[i][j] = = 0) {Row[i] = column[j] = true;continue;}}} for (int i = 0; i < rows; ++i) {if (!row[i]) continue;for (int j = 0; j < columns; ++j) {matrix[i][j] = 0;}} for (int j = 0; j < columns; ++j) {if (!column[j]) continue;for (int i = 0; i < rows; ++i) {matrix[i][j] = 0;}}




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