Spiral Matrix II — LeetCode 59 Python Solution
MediumArrayMatrixSimulation
- Problem
- #59
- Pattern
- Matrix and Grid
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.
Example
- Input
- n = 3
- Output
- [[1,2,3],[8,9,4],[7,6,5]]
Python solution
Python
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
ans = [[0] * n for _ in range(n)]
dirs = (0, 1, 0, -1, 0)
i = j = k = 0
for v in range(1, n * n + 1):
ans[i][j] = v
x, y = i + dirs[k], j + dirs[k + 1]
if x < 0 or x >= n or y < 0 or y >= n or ans[x][y]:
k = (k + 1) % 4
i, j = i + dirs[k], j + dirs[k + 1]
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2), where n is the side length of the matrix |
| Space | O(1) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 59. Spiral Matrix II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Matrix.
The matrix and grid guide has the Python template for the pattern and the 216 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 59. Spiral Matrix II?
- LeetCode 59. Spiral Matrix II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 59. Spiral Matrix II?
- The Python solution on this page runs in O(n^2), where n is the side length of the matrix.
- What is the space complexity of LeetCode 59. Spiral Matrix II?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 59. Spiral Matrix II cover?
- LeetCode 59. Spiral Matrix II is tagged Array, Matrix and Simulation on LeetCode.