diff --git a/01-matrix/solution.py b/01-matrix/solution.py index 64a2460..df81e81 100644 --- a/01-matrix/solution.py +++ b/01-matrix/solution.py @@ -40,6 +40,7 @@ The cells are adjacent in only four directions: up, down, left and right. ''' + class Solution(object): def updateMatrix(self, matrix): """ @@ -47,3 +48,59 @@ def updateMatrix(self, matrix): :rtype: List[List[int]] """ + for i, row in enumerate(matrix): + for j, c in enumerate(row): + if c != 0: + row[j] = len(matrix) + len(row) + 1 + + current = 0 + changed = True + + while changed: + changed = False + for i, row in enumerate(matrix): + for j, c in enumerate(row): + if c != current: + continue + + # up + if i > 0 and matrix[i-1][j] > current+1: + matrix[i-1][j] = current+1 + changed = True + + # down + if i < len(matrix)-1 and matrix[i+1][j] > current+1: + matrix[i+1][j] = current+1 + changed = True + + # left + if j > 0 and matrix[i][j-1] > current+1: + matrix[i][j-1] = current+1 + changed = True + + # right + if j < len(row)-1 and matrix[i][j+1] > current+1: + matrix[i][j+1] = current+1 + changed = True + + current+=1 + return matrix + +def main(): + s = Solution() + + matrix = [[0, 0, 0], [0, 1, 0], [0, 0, 0]] + output = [[0, 0, 0], [0, 1, 0], [0, 0, 0]] + s.updateMatrix(matrix) + print(matrix) + assert(output == matrix) + + matrix = [[0, 0, 0], [0, 1, 0], [1, 1, 1]] + output = [[0, 0, 0], [0, 1, 0], [1, 2, 1]] + s.updateMatrix(matrix) + print(matrix) + assert(output == matrix) + + +if __name__ == '__main__': + main()