Set Matrix Zeros

Source: Internet
Author: User

Problem description

Given a m x n Matrix, if an element was 0, set its entire row and column to 0. Do it on place.

Solution Ideas

The difficulty is how to not use the secondary space.

A clever idea is that

1. Using two tag variables, Row0_has_zeros and Col0_has_zeros indicate whether the first row and the first column in the matrix contain 0 elements, respectively;

2. Start the traversal from the inner element of the matrix, and if the matrix element is 0, set the corresponding first row and first column alignment elements to 0;

3. From the inner element of the matrix to start the traversal, the process of traversal, check the corresponding first row and the first column element is 0, if 0, the element is set to 0;

4. Finally, based on the two tag variables, decide whether you need to set all the elements of the first row and the first column to 0.

The time complexity is O (n^2) and the space complexity is O (1).

Program

public class Solution {public    void Setzeroes (int[][] matrix) {        if (Matrix = = NULL | | matrix.length = = 0 | | matrix [0].length = = 0) {return;} Boolean Row0_has_zeros = False;boolean Col0_has_zeros = false;for (int i = 0; i < matrix[0].length; i++) {if (matrix[0] [i] = = 0) {Row0_has_zeros = True;break;}} for (int i = 0; i < matrix.length; i++) {if (matrix[i][0] = = 0) {Col0_has_zeros = True;break;}} for (int i = 1, i < matrix.length; i++) {for (int j = 1; j < Matrix[0].length; J + +) {if (matrix[i][j] = = 0) {matrix[ 0][J] = 0;matrix[i][0] = 0;}}} for (int i = 1, i < matrix.length; i++) {for (int j = 1; j < Matrix[0].length; J + +) {if (matrix[0][j] = = 0 | | matrix I [0] = = 0) {Matrix[i][j] = 0;}}} if (Row0_has_zeros) {for (int i = 0; i < matrix[0].length; i++) {matrix[0][i] = 0;}} if (Col0_has_zeros) {for (int i = 0; i < matrix.length; i++) {matrix[i][0] = 0;}}}    

Set Matrix Zeros

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.