leetcode专题训练 59. Spiral Matrix II

这道题与54题很像而且比那道简单。
附上54题题解:https://blog.csdn.net/Ema1997/article/details/100838015

import numpy as np

class Solution:
    dir = [[-1, 0], [1, 0], [0, -1], [0, 1]]
    
    def generateMatrix(self, n: int) -> List[List[int]]:
        result = [[0]*n for i in range(n)]
        right = down = n-1
        left = up = 0
        x = y = 0
        d = 3 # 0上1下2左3右
        for i in range(1, n*n+1):
            result[x][y] = i
            if x == up and y == right and d == 3:
                d = 1
                up += 1
            elif x == down and y == right and d == 1:
                d = 2
                right -= 1
            elif x == down and y == left and d == 2:
                d = 0
                down -= 1
            elif x == up and y == left and d == 0:
                d = 3
                left += 1
            x = x + self.dir[d][0]
            y = y + self.dir[d][1]
        return result
发布了201 篇原创文章 · 获赞 26 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/Ema1997/article/details/101643026