Spiral Matrix — LeetCode 54 Python Solution
MediumArrayMatrixSimulation
- Problem
- #54
- Pattern
- Matrix and Grid
- Reading time
- 3 min
- Source
- leetcode.com
The problem
Given an m x n matrix, return all elements of the matrix in spiral order.
Example
- Input
- matrix = [[1,2,3],[4,5,6],[7,8,9]]
- Output
- [1,2,3,6,9,8,7,4,5]
Python solution
Python
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
m, n = len(matrix), len(matrix[0])
dirs = (0, 1, 0, -1, 0)
vis = [[False] * n for _ in range(m)]
i = j = k = 0
ans = []
for _ in range(m * n):
ans.append(matrix[i][j])
vis[i][j] = True
x, y = i + dirs[k], j + dirs[k + 1]
if x < 0 or x >= m or y < 0 or y >= n or vis[x][y]:
k = (k + 1) % 4
i += dirs[k]
j += dirs[k + 1]
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n) |
| Space | O(m \times n) auxiliary |
Pattern: Matrix and Grid
Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 54. Spiral Matrix 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
On study lists
This problem is on Blind 75, NeetCode 150, Grind 75 and Top Interview 150.
Frequently asked questions
- How hard is LeetCode 54. Spiral Matrix?
- LeetCode 54. Spiral Matrix is rated Medium on LeetCode.
- What is the time complexity of LeetCode 54. Spiral Matrix?
- The Python solution on this page runs in O(m \times n).
- What is the space complexity of LeetCode 54. Spiral Matrix?
- The Python solution on this page uses O(m \times n) auxiliary space.
- What topics does LeetCode 54. Spiral Matrix cover?
- LeetCode 54. Spiral Matrix is tagged Array, Matrix and Simulation on LeetCode.