首页 > 试题广场 >

螺旋矩阵-ii

[编程题]螺旋矩阵-ii
  • 热度指数:10802 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
给定一个整数n,将数字1到按螺旋的顺序填入n×n的矩阵
例如:
给出的n=3,
你应该返回如下矩阵:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
示例1

输入

2

输出

[[1,2],[4,3]]
#

# @param n int整型 
# @return int整型二维数组
#
class Solution:
    def generateMatrix(self , n ):
        # write code here
    # write code here
        if n == 0:
            a = []
            return a
        dr = [[0, 1], [1, 0], [0, -1], [-1, 0]]
        nx, ny = 0, 0
        x, y = 0, 0
        nd = 0
        arr = [[0 for i in range(n)] for j in range(n)]
        for i in range(1, n * n + 1):
            arr[x][y] = i
            nx = x + dr[nd][0]
            ny = y + dr[nd][1]
            if 0 <= nx < n and 0 <= ny < n and arr[nx][ny] == 0:
                x = nx
                y = ny
            else:
                nd = (nd + 1) % 4
                x = x + dr[nd][0]
                y = y + dr[nd][1]
        return arr



定义方向矩阵,右下左上,然后判断只要在行和列的范围内,并且下一格是0,就把数字写入,超过行列范围就nd改方向。
发表于 2020-07-17 10:04:36 回复(0)