55. Set matrix zeroes

Source: Internet
Author: User
Set matrix zeroes

(Link: https://oj.leetcode.com/problems/set-matrix-zeroes)

GivenMXNMatrix, if an element is 0, set its entire row and column to 0. Do it in 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 not the best solution. cocould you devise a constant space solution?

Idea: Find the first zero element and write down its rows and columns. Then, the other 0 elements are projected into the recorded rows and columns (marked) respectively ). After the traversal, the column where all rows are marked is set to 0; for all columns, the row where all columns are marked is set to 0. (the last row and column marked with 0. time: O (n2), Space: O (1)

class Solution {public:void setZeroes(vector<vector<int> > &matrix) {if(!matrix.size() || !matrix[0].size()) return;const int INF = 1001;int row = matrix.size(), col = matrix[0].size();int u = -1, v = -1;for(int r = 0; r < row; ++r) for(int c = 0; c < col; ++c) {if(matrix[r][c] == 0) {if(u == -1) {  u = r, v = c; continue; }matrix[u][c] = INF;matrix[r][v] = INF;}}if(u == -1) return;if(matrix[u][v] == INF) matrix[u][v] = 0;for(int c = 0; c < col; ++c) {if(matrix[u][c] == INF) {for(int i = 0; i < row; ++i)  matrix[i][c] = 0;} else matrix[u][c] = 0;}for(int r = 0; r < row; ++r) {if(matrix[r][v] == INF) {for(int j = 0; j < col; ++j) matrix[r][j] = 0;} else matrix[r][v] = 0;}}};

 

 

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