Set the row and column of the element with value 0 in the matrix to 0, in-place O (1) Space O (MN) time

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?

public class Solution {public void setzeroes (int[][] matrix) {int m=matrix.length;        if (m==0) return;        int n=matrix[0].length;        if (n==0) return;        Boolean prezeros=false;        Boolean curzeros=false;            for (int i=0;i<m;i++) {//test If this row has zeros. for (int j=0;j<n;j++) {if (matrix[i][j]==0) {for (int k=0;k&                    lt;i;k++) matrix[k][j]=0;                Curzeros=true;            }}//fill the zeros along Coloum.                    if (i>0) {for (int j=0;j<n;j++) {if (matrix[i-1][j]==0)                    {matrix[i][j]=0;            }}}//if pre row have zeros, fill zeros with that row. if (Prezeros) {for (int J=0;j<n;j++) {matrix[i-1][j]=0;            }} Prezeros=curzeros;        Curzeros=false;            } if (Prezeros) {for (int j=0;j<n;j++) {matrix[m-1][j]=0; }        }    }}



Set the row and column of the element with value 0 in the matrix to 0, in-place O (1) Space O (MN) time

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.