[leetcode]73. Set Matrix Zeroes to 0

Posted by glowball on Sat, 02 Nov 2019 10:57:19 +0100

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.

Example 1:

Input: 
[
  [1,1,1],
  [1,0,1],
  [1,1,1]
]
Output: 
[
  [1,0,1],
  [0,0,0],
  [1,0,1]
]

Example 2:

Input: 
[
  [0,1,2,0],
  [3,4,5,2],
  [1,3,1,5]
]
Output: 
[
  [0,0,0,0],
  [0,4,5,0],
  [0,3,1,0]
]

 

 

meaning of the title

Given a matrix, as long as an element is 0, set the corresponding entire row and column to 0.

 

Train of thought:

The topic requires O(1) space, reuse the first row and the first column as reference.

 

If the input matrix is:

1. Scan the first row first, and mark the position of 0; then scan the first column, and mark the position of 0

  

2. Use the first row and the first column as a reference to process the rest of the matrix: scan matrix[i][j]. If it is 0, reverse the first row and the first column to fill 0 (mark)

      

3. Scan matrix[i][j] again. If the first row and the first column are marked with fill 0, fill myself as 0

     

 

       

 

4. Finally handle the first row and the first column of the reference

 

Code

 1 class Solution {
 2     public void setZeroes(int[][] matrix) {
 3         final int rowLen = matrix.length;
 4         final int colLen = matrix[0].length;
 5         boolean row_has_zero = false; // Does the first row have a 0
 6         boolean col_has_zero = false; // Does the first column have 0
 7 
 8         for (int j = 0; j < colLen; j++){
 9             if (matrix[0][j] == 0) {
10                 row_has_zero = true;
11                 break;
12             }
13         }
14 
15         for (int i = 0; i < rowLen; i++){
16             if (matrix[i][0] == 0) {
17                 col_has_zero = true;
18                 break;
19             }
20         }
21 
22         for (int i = 1; i < rowLen; i++){
23             for (int j = 1; j < colLen; j++){
24                 if (matrix[i][j] == 0) {
25                     matrix[0][j] = 0;
26                     matrix[i][0] = 0;
27                 }
28             }
29         }
30 
31         for (int i = 1; i < rowLen; i++){
32             for (int j = 1; j < colLen; j++){
33                 if (matrix[i][0] == 0 || matrix[0][j] == 0){matrix[i][j] = 0;}
34             }
35         }
36         //Not first fill The first row and the first column, because the first row and the first column are used as references
37         if (row_has_zero){
38             for (int j = 0; j < colLen; j++){
39                 matrix[0][j] = 0;
40             }
41         }
42         if (col_has_zero){
43             for (int i = 0; i < rowLen; i++){
44                 matrix[i][0] = 0;
45             }
46         }
47     }
48 }

Topics: PHP REST