MediumNo. 0885

Spiral Matrix III — LeetCode 885 Python Solution

Topics
Array, Matrix, Simulation
Reading time
3 min

The problem

You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.

Example

Input
rows = 1, cols = 4, rStart = 0, cStart = 0
Output
[[0,0],[0,1],[0,2],[0,3]]

Python solution

PythonSolution
class Solution:
    def spiralMatrixIII(
        self, rows: int, cols: int, rStart: int, cStart: int
    ) -> List[List[int]]:
        ans = [[rStart, cStart]]
        if rows * cols == 1:
            return ans
        k = 1
        while True:
            for dr, dc, dk in [[0, 1, k], [1, 0, k], [0, -1, k + 1], [-1, 0, k + 1]]:
                for _ in range(dk):
                    rStart += dr
                    cStart += dc
                    if 0 <= rStart < rows and 0 <= cStart < cols:
                        ans.append([rStart, cStart])
                        if len(ans) == rows * cols:
                            return ans
            k += 2

Complexity

Time
O(m·n)
Space · auxiliary
O(1) to O(m·n)

Pattern: Matrix and Grid

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells. LeetCode 885. Spiral Matrix III 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
0054Spiral MatrixMedium
0059Spiral Matrix IIMedium
0289Game of LifeMedium
0498Diagonal TraverseMedium
0566Reshape the MatrixEasy
0867Transpose MatrixEasy

Frequently asked questions

How hard is LeetCode 885. Spiral Matrix III?

LeetCode 885. Spiral Matrix III is rated Medium on LeetCode.

What topics does LeetCode 885. Spiral Matrix III cover?

LeetCode 885. Spiral Matrix III 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.