Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time

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

My code:

class Solution:
    def setZeroes(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: void Do not return anything, modify matrix in-place instead.
        """
        if len(matrix)==0:
            return
        m=len(matrix)
        example=matrix[0]
        if len(matrix)==0:
            return
        n=len(example)
        lists=set()
        for i in range(m):
            for j in range(n):
                if matrix[i][j]==0:
                    lists.add(i*n+j)
        tmp_column={}
        tmp_row={}
        for item in lists:
            column=item%n
            row=int((item-column)/n)
            #print(column)
            #print(row)
            if row not in tmp_row:
                tmp_row[row]=0
                for k in range(n):
                    matrix[row][k]=0
            if column not in tmp_column:
                tmp_column[column]=0
                for k in range(m):
                    matrix[k][column]=0

Solution: https://leetcode.com/problems/set-matrix-zeroes/