The matrix zero

Write an algorithm to zero the rows and columns of an M by N matrix if any element is zero.

Example 1:

,1,1 input: [[1], [1, 1], [1,1,1]] output: [[1, 1], [0, 0], [1, 1]] example 2:

,1,2,0 input: [[0], [3,4,5,2], [1,3,1,5]] output: [,0,0,0 [0], [0,4,5,0], [0,3,1,0]]

Create two one-dimensional arrays to store the rows and columns to be cleaned, iterate over them first, save the rows and columns to be cleaned, and then iterate over and modify them. If you can use a two-dimensional array, you can also read the original array to be modified, and modify it in the new array. Java

class Solution {
    public void setZeroes(int[][] matrix) {
        boolean[] line = new boolean[matrix.length];
        boolean[] column = new boolean[matrix[0].length];
        // Find the row to be cleared
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                if (matrix[i][j] == 0) {
                    line[i] = true;
                    column[j] = true; }}}// start clearing rows
        for (int i = 0; i < matrix.length; i++) {
            if (line[i]) {
                for (int j = 0; j < matrix[0].length; j++) {
                    matrix[i][j] = 0; }}}// start zeroing columns
        for (int i = 0; i < matrix[0].length; i++) {
            if (column[i]) {
                for (int j = 0; j < matrix.length; j++) {
                    matrix[j][i] = 0;
                }
            }
        }

    }
}
Copy the code

python

import copy
class Solution(object):
    def setZeroes(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: None Do not return anything, modify matrix in-place instead.
        """
        res_x=[]
        res_y=[]
        for i in range(len(matrix)):
            for j in range(len(matrix[0)) :if matrix[i][j]==0:
                    res_x.append(i)
                    res_y.append(j)
        for math in range(len(res_x)):
            for x in res_x:
                for m in range(len(matrix[0])):
                    matrix[x][m]=0
            for y in res_y:
                for n in range(len(matrix)):
                    matrix[n][y]=0
        return matrix
        # res=copy.deepcopy(matrix)
        # for i in range(len(matrix)):
        # for j in range(len(matrix[0])):
        #         if matrix[i][j]==0:
        # for x in range(len(matrix)):
        # res[x][j]=0
        # print(res[x][j])
        # for y in range(len(matrix[0])):
        # res[i][y]=0
        # return res
Copy the code