[Leetcode] 73. Set Matrix Zeroes matrix set to 0

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]
]

 

 

The meaning of problems

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

 

Ideas:

Topics requirements O (1) space, the first column of the first row multiplexed as a reference.

 

If the input matrix is:

1. The first line of the first sweep, the marking of the position 0; then sweep a first row, would mark the position of 0

  

2. The first row and first column as a reference, the remaining portion of the processing matrix: sweep matrix [i] [j], if 0, the reverse to the first row and first column Fill 0 (mark)

      

3. then sweep matrix [i] [j], if the corresponding row and first column before the first fill 0 has a flag, the fill myself as 0 

     

 

       

 

4. Finally, the first row and first column process their 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; // 第一行是否存在 0
 6         boolean col_has_zero = false; // 第一列是否存在 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         //不能先fill第一行和第一列,因为把第一行第一列当成了参照
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 }

 

Guess you like

Origin www.cnblogs.com/liuliu5151/p/10953109.html