Medium
Array
Matrix
59. Spiral Matrix II
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
n
n x n
matrix
1
Example 1:
Input: n = 3 Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1 Output: [[1]]
Constraints:
偷懶拿昨天的 code 改寫
class Solution: def generateMatrix(self, n: int) -> List[List[int]]: directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] d = 0 sx, sy = 0, 0 matrix = [[0] * n for _ in range(n)] fill_val = 1 matrix[sx][sy] = fill_val while fill_val < n * n: dx, dy = directions[d % 4] nx, ny = sx + dx, sy + dy if 0 <= nx < n and 0 <= ny < n and not matrix[nx][ny]: fill_val += 1 matrix[nx][ny] = fill_val sx, sy = nx, ny else: d += 1 return matrix
Ron ChenWed, May 10, 2023
回到題目列表
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up