leetcode:set-matrix-zeroes(Java实现)

Title description

Given an m*n matrix, if one element is 0, set all the elements in the row and column where the element is located to 0, requiring the use of the in-place algorithm.

expand:

Does your algorithm use extra space?

A more straightforward algorithm is to use O(m,n) space, but this is not a good solution

Using simple improvements can solve this problem in O(m+n) space, but it is not the best solution yet

Can you solve this problem within a constant level of space complexity?

 

Idea: Set up an auxiliary array fuzu[][] with the same length and width as the original array. And initialize all elements to 0, scan the matrix array row by row, column by row, and if any element is 0, assign the auxiliary array element at the same position to 1. Then scan the auxiliary array once if there is an element of 1, then all the elements in the row and column of the matrix array at the corresponding position are assigned to 0.

Java special usage: Arrays.fill() method, not elaborated here.

import java.util.Arrays;
public class Solution {
    public void setZeroes(int[][] matrix) {
          int i,j;

    //获取二维数组的长和宽
        int height=matrix.length;
        int width=matrix[0].length;

        int fuzu[][]=new int[height][width];
        for(i=0;i<height;i++)
            Arrays.fill(fuzu[i],0);

        for(i=0;i<height;i++)
            for(j=0;j<width;j++){
                if(matrix[i][j]==0)
                    fuzu[i][j]=1;
            }
        for(i=0;i<height;i++)
            for(j=0;j<width;j++){
                if(fuzu[i][j]==1){
                    for(int n=0;n<width;n++)
                        matrix[i][n]=0;
                    for(int m=0;m<height;m++)
                        matrix[m][j]=0;
                }
            }
    }
}

 

Guess you like

Origin blog.csdn.net/Zhongtongyi/article/details/107294930