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

示例:

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

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/spiral-matrix-ii
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
"""

from typing import *


def generateMatrix(n: int) -> List[List[int]]:
    matrix = [[0 for _ in range(n)] for _ in range(n)]
    count, l, r, u, d = 1, 0, n-1, 0, n-1
    while l <= r and u <= d:
        if l == r and u == d:
            matrix[l][u] = count
            count += 1
        else:
            for j in range(l, r):
                matrix[u][j] = count
                count += 1
            for i in range(u, d):
                matrix[i][r] = count
                count += 1
            for j in range(r, l, -1):
                matrix[d][j] = count
                count += 1
            for i in range(d, u, -1):
                matrix[i][l] = count
                count += 1
        l, r, u, d = l+1, r-1, u+1, d-1
    return matrix


if __name__ == '__main__':
    print(generateMatrix(3))
