My AC Python code

  • 0

    The idea is to find zeros and assign their rows and cols. If you want to do the finding on the fly, be careful, just treat those original zeros (skip those assigned zeros).

    class Solution(object):
        def setZeroes(self, matrix):
            :type matrix: List[List[int]]
            :rtype: void Do not return anything, modify matrix in-place instead.
            m = len(matrix)
            if m == 0:  return
            n = len(matrix[0])
            if n == 0:  return
            visited = [[False for j in range(n)] for i in range(m)]
            for i in xrange(m):
                for j in xrange(n):
                    if matrix[i][j] == 0 and visited[i][j] == False:
                        # treat the same row
                        for k in xrange(n): 
                            if matrix[i][k] != 0:
                                matrix[i][k] = 0
                                visited[i][k] = True
                        # treat the same col        
                        for k in xrange(m): 
                            if matrix[k][j] != 0:
                                matrix[k][j] = 0
                                visited[k][j] = True
                        # label it as True
                        visited[i][j] = True

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.