59. 螺旋矩阵 II

给定一个正整数 n,生成一个包含 1 到 n^ 2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3
输出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

解法

  • class Solution:
      def generateMatrix(self, n: int) -> List[List[int]]:
          matrix = [[0 for _ in range(n)] for _ in range(n)]
          dire = [[0,1],[1,0],[0,-1],[-1,0]]
          index = 0
          cur_i,cur_j,count = 0,0,1
          for i in range(n**2):
              matrix[cur_i][cur_j] = count
              count += 1
              nex_i,nex_j = cur_i+dire[index][0],cur_j+dire[index][1]
              if (0<=nex_i<n) and (0<=nex_j<n) and (matrix[nex_i][nex_j]==0):
                  cur_i,cur_j = nex_i,nex_j
              else:
                  index = (index+1)%4
                  cur_i,cur_j = cur_i+dire[index][0],cur_j+dire[index][1]
          return matrix
    

题目改写

生成一个斐波那契数列的正方形矩阵,例如:

例如 n = 3
34 21 13
 1  1  8
 2  3  5

n = 4
987 610 377 233
  5   3   2 144
  8   1   1  89
 13  21  34  55

代码如下:

def generateMatrix(n):
    ### 生成斐波那契数列数列
    def fib(n):
        if n == 1: return [1]
        dp = [0]*(n**2)
        dp[0],dp[1] = 1,1
        for i in range(2,n**2):
            dp[i] = dp[i-1]+dp[i-2]
        return dp

    res = fib(n)
    matrix = [[0]*n for _ in range(n)]
    dire = [[0,1],[1,0],[0,-1],[-1,0]]
    index = 0
    cur_i,cur_j,count = 0,0,n**2-1
    for i in range(n**2):
        matrix[cur_i][cur_j] = res[count]
        count -= 1
        nex_i,nex_j = cur_i+dire[index][0],cur_j+dire[index][1]
        if (0<=nex_i<n) and (0<=nex_j<n) and matrix[nex_i][nex_j]==0:
            cur_i,cur_j = nex_i,nex_j
        else:
            index = (index+1)%4
            cur_i,cur_j = cur_i+dire[index][0],cur_j+dire[index][1]
    return matrix
print(generateMatrix(5))
[[75025, 46368, 28657, 17711, 10946],
 [55, 34, 21, 13, 6765],
 [89, 1, 1, 8, 4181],
 [144, 2, 3, 5, 2584],
 [233, 377, 610, 987, 1597]]