[leetcode] 59. Spiral Matrix II @ python

原题

Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

解法

首先初始化n*n的0矩阵, 然后定义向右, 向下, 向左, 向上的方向, 遍历n次, 每次将数字i 赋值给矩阵的某个位置, 这里位置的确定条件是当下一个位置的index在矩阵范围之内并且下一个位置的值为0时, 我们按照当前方向走, 否则改变方向并更新x, y的值.

代码

class Solution(object):
    def generateMatrix(self, n):
        """
        :type n: int
        :rtype: List[List[int]]
        """
        res = [[0]*n for _ in range(n)]
        # directions for right, down, left, up
        directions = [(0, 1), (1,0), (0,-1), (-1,0)]
        x, y, d = 0, 0, 0
        for i in range(1, n**2+1):
            res[x][y] = i
            dx, dy = directions[d%4]
            if 0 <= x+dx < n and 0<= y+dy < n and res[x+dx][y+dy] == 0:
                # move according to the current direction
                x, y = x+dx, y+dy
            else:
                # change direction
                d += 1
                dx, dy = directions[d%4]
                x, y = x+dx, y+dy
                
        return res

你可能感兴趣的:(Leetcode)