Try   HackMD

59.Spiral Matrix II

tags: 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.

範例

Example 1:

Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]

Example 2:

Input: n = 1
Output: [[1]]

Constraints:

  • 1 <= n <= 20

解答

Python

偷懶拿昨天的 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

Reference

回到題目列表