7-line Python solution, step pattern is n, n-1, n-1, n-2, n-2 ..., 2, 2, 1, 1


  • 3
    K

    If n is 5, step list will be [5, 4, 4, 3, 3, 2, 2, 1, 1], it means move forward 5 steps, turn right, move forward 4 steps, turn right, move forward 4 steps, turn right and so on. x axis is from left to right, y axis is from top to bottom, we start from point (-1, 0).

    def generateMatrix(self, n):
        mat, x, y, dx, dy, number = [[0] * n for i in xrange(n)], -1, 0, 1, 0, 0
        for step in [i / 2 for i in xrange(2 * n, 1, -1)]:
            for j in xrange(step):
                x, y, number = x + dx, y + dy, number + 1
                mat[y][x] = number
            dx, dy = -dy, dx # turn right
        return mat

Log in to reply
 

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