Solution of zero matrix problem

topic

Write an algorithm to clear the row and column where an element in an M × N matrix is ​​0.

Example 1:

输入:
[
  [1,1,1],
  [1,0,1],
  [1,1,1]
]
输出:
[
  [1,0,1],
  [0,0,0],
  [1,0,1]
]

Example 2:


输入:
[
  [0,1,2,0],
  [3,4,5,2],
  [1,3,1,5]
]
输出:
[
  [0,0,0,0],
  [0,4,5,0],
  [0,3,1,0]
]

analyze

In the matrix, if you encounter 0a value of , press the cross to clear the value of the row and column. Think about how to achieve it.

First of all, the given matrix is ​​a square matrix, and the width and height are not necessarily the same. So pay attention to the width and height when defining temporary array storage.

The first thing that comes to mind is 遍历矩阵that if you encounter something 0that will be 当前行converted 当前列to data 0, this method is possible, but you should pay attention to the modified row and column 不能参与后面的数据判断, otherwise the modified value and the original data will be generated 混淆. So if you use this method, you need to mark the rows and columns as modified values.

insert image description here

If the marking and value refreshing are performed in a cycle, it is a bit confusing and difficult to sort out, so it will be divided 标记into 值刷新two steps. First define the sum of 宽高两个数组as , and then traverse the two arrays, and if it is, clear the row and column data of the corresponding matrix.0truetrue

code show as below:

    public void setZeroes(int[][] matrix) {
    
    
        boolean row[] = new boolean[matrix.length];
        boolean vertical[] = new boolean[matrix[0].length];
        for(int i = 0; i < matrix.length;i++){
    
    
            int now[] = matrix[i];
            for (int j = 0; j < now.length; j++) {
    
    
                if (now[j] == 0){
    
    
                    row[i] = true;
                    vertical[j] = true;
                }
            }
        }

        for (int i = 0; i < row.length; i++) {
    
    
            int now[] = new int[matrix[0].length];
            if (row[i]){
    
    
                matrix[i] = now;
            }
        }

        for (int i = 0; i < vertical.length; i++) {
    
    
            if (vertical[i]){
    
    
                for (int j = 0; j < matrix.length; j++) {
    
    
                    matrix[j][i] = 0;
                }
            }
        }
    }

Results of the:

insert image description here

Guess you like

Origin blog.csdn.net/AnNanDu/article/details/126746674