Leetcode:set Matrix Zeroes

Source: Internet
Author: User

Set Matrix Zeroes


Total Accepted: 67555 Total Submissions: 200621 Difficulty: Medium

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.

Subscribe to see which companies asked this question

Hide TagsArrayHide Similar Problems(M) Game of Life















Ideas:

0 1 2 5
4 3 1 4
0 1 0 4
1 2 1 3
2 0 1 1



(1) Set the first row, first column element to 0

0 0 0 5
4 3 1 4
0 1 0 4
1 2 1 3
0 0 1 1



(2) sets the row in [1,m-1],col in [1,n-1] whether the element is 0

0 0 0 5
4 0 0 4
0 0 0 0
1 0 0 3
0 0 0 0


(3) Final processing of first row, first column
0 00 0
0 0 0 4
0 0 0 0
0 0 0 3
0 0 0 0


Java code:

public                Class Solution {public void setzeroes (int[][] matrix) {Boolean firstrow = False, Firstcol = false;        int rows = Matrix.length;                int cols = Matrix[0].length;                    for (int i=0;i<rows;i++) {for (int j=0;j<cols;j++) {if (matrix[i][j]==0) {                    if (i==0) FirstRow = true;                                        if (j==0) Firstcol = true;                MATRIX[I][0]=MATRIX[0][J] = 0;                }}} for (int i=1;i<rows;i++) {for (int j=1;j<cols;j++) {            if (matrix[i][0]==0 | | matrix[0][j]==0) MATRIX[I][J] = 0;                }} if (FirstRow) for (int i=0;i<cols;i++) matrix[0][i] = 0;            if (Firstcol) for (int j=0;j<rows;j++) matrix[j][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.