MediumNo. 0054

Spiral Matrix — LeetCode 54 Python Solution

Topics
Array, Matrix, Simulation
Reading time
3 min

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

PythonSolution
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 ans

Complexity

Time
O(m × n)
Space · auxiliary
O(m × n)

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

Related problems
No.ProblemDifficulty
0059Spiral Matrix IIMedium
0885Spiral Matrix IIIMedium
2326Spiral Matrix IVMedium
0289Game of LifeMedium
0498Diagonal TraverseMedium
0566Reshape the MatrixEasy

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 × n).

What is the space complexity of LeetCode 54. Spiral Matrix?

The Python solution on this page uses O(m × n) auxiliary space.

What topics does LeetCode 54. Spiral Matrix cover?

LeetCode 54. Spiral Matrix is tagged Array, Matrix and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.