Problem
Given a positive integer n
, generate an n x n
matrix
filled with elements from 1
to n²
in spiral order.
https://leetcode.cn/problems/spiral-matrix-ii/
Example 1:
Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1
Output: [[1]]
Constraints:
Test Cases
1 2
| class Solution: def generateMatrix(self, n: int) -> List[List[int]]:
|
solution_test.py1 2 3 4 5 6 7 8 9 10 11 12
| import pytest
from solution import Solution
@pytest.mark.parametrize('n, expected', [ (3, [[1,2,3],[8,9,4],[7,6,5]]), (1, [[1]]), ]) @pytest.mark.parametrize('sol', [Solution()]) def test_solution(sol, n, expected): assert sol.generateMatrix(n) == expected
|
Thoughts
跟 54. Spiral Matrix 类似,完全一样的遍历顺序,只是读出还是写入的区别。直接把代码搬过来,把 res[idx] = matrix[i][j]
替换成 matrix[i][j] = idx + 1
,m 改成 n,基本就可以了。
Code
solution.py1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution: def generateMatrix(self, n: int) -> list[list[int]]: matrix = [[0] * n for _ in range(n)] steps = ((0, 1), (1, 0), (0, -1), (-1, 0)) limits = [n, n - 1] i = 0 j = -1 dir = 0 move = 0 for idx in range(1, n * n + 1): i += steps[dir][0] j += steps[dir][1] matrix[i][j] = idx move += 1 if move == limits[dir & 1]: limits[dir & 1] -= 1 dir = (dir + 1) % 4 move = 0
return matrix
|