IMMENSE.LY

IT’S THAT BIG

Set Matrix Zeros

Much like the Rotation Matrix, the “Set Matrix Zeros” problem involves being careful about not destroying the existing matrix which is being operated on. The idea is that given a cell in the matrix which is set to zero, set all of the other cells in the same row or column to zero.

I tackled this in two ways which are almost identical. First up was just making a copy of the initial matrix and working on that instead. Here’s the code:

import copy

def zeroMatrix1(mtrx):
    newMtrx = copy.deepcopy(mtrx)

    def zeroRowCol(r, c):
        for n in range(len(mtrx)):
            newMtrx[n][c] = 0
        for n in range(len(mtrx[0])):
            newMtrx[r][n] = 0

    for r in range(len(mtrx)):
        for c in range(len(mtrx[0])):
            if not mtrx[r][c]:
                zeroRowCol(r, c)
    return newMtrx

The deepcopy is important here otherwise you end up with a copy of the original matrix and you’ll be operating on that instead. There’s not really a “trick” here per se, but the key is if we hadn’t made the copy and zeroRowCol() operated on the original matrix, it would fill in everything with lots of zeros.

Since making a copy of the matrix is expensive, there is a way of doing this by just keeping track of any cells we found that had a zero, and calling zeroRowCol() later. That looks like this:

``` def zeroMatrix2(mtrx): def zeroRowCol(r, c): for n in range(len(mtrx)): mtrx[n][c] = 0 for n in range(len(mtrx[0])): mtrx[r][n] = 0

points = list()

for r in range(len(mtrx)):
    for c in range(len(mtrx[0])):
        if not mtrx[r][c]:
            points.append((r, c))

for p in points:
    zeroRowCol(*p)

return mtrx
```