If we can't write data to the matrix, we change the direction,a simple python solution


  • 8
    T
    class Solution:
    # @return a list of lists of integer
    def generateMatrix(self, n):
        matrix = [[0]*n for _ in range(n)]
        directions = ((0, 1), (1, 0), (0, -1), (-1, 0))
        d = 0
        y, x = 0, 0
        for i in range(1, n*n+1):
            matrix[y][x] = i
            dy, dx = directions[d % 4]
            if -1 < y+dy < n and -1 < x+dx < n and matrix[y+dy][x+dx] == 0:
                y, x = y+dy, x+dx
            else:
                d += 1
                dy, dx = directions[d % 4]
                y, x = y+dy, x+dx
        return matrix
    

    Change the direction If the we can't write to the matrix


  • 0
    H

    exactly what I thought. However, i do not figure out how to use direction elegantly.


Log in to reply
 

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