Monday, August 17, 2015

Leetcode 73. Set Matrix Zeroes

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

The main problem is how to avoid setting those that are in a row or column with 0  to 0s, for if in that case, the whole matrix will be all zeros. So we should tell from original zeros from set zeros. One way to do that is to replace 0 with another character.

Solution:
# T:O(m*n) S:O(1)
class Solution:
    # @param {integer[][]} matrix
    # @return {void} Do not return anything, modify matrix in-place instead.
    def setZeroes(self, matrix):
        m, n = len(matrix), len(matrix[0])
        for i in xrange(m):
            for j in xrange(n):
                if matrix[i][j] == 0:
                    for k in xrange(n):
                        if matrix[i][k] != 0:
                            matrix[i][k] = 'X'
                    for k in xrange(m):
                        if matrix[k][j] != 0:
                            matrix[k][j] = 'X'
        for i in xrange(m):
            for j in xrange(n):
                if matrix[i][j] == 'X':
                    matrix[i][j] = 0
Run Time: 208 ms

No comments:

Post a Comment