Problem 885

Abstract / Summary

Generate a sequence of coordinates in a clockwise spiral starting from the origin and moving outward on a grid.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0885.py

class Solution:
    def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]:
        x = cStart
        y = rStart

        deltas = [ [ +1, 0], [ 0, +1 ], [ -1, 0 ], [ 0, -1] ]
        direction = 0
        dx, dy = deltas[direction]

        steps  = 1
        xsteps = ysteps = steps

        found = 0
        size  = rows * cols
        while found < size:
            if 0 <= x < cols and 0 <= y < rows:
                yield y, x # row, col
                found += 1

            if dx != 0:
                x += dx
                xsteps -= abs(dx)
                if xsteps == 0:
                    direction += 1
                    dx, dy = deltas[direction]
                    steps += 1
                    xsteps = steps
            else: # dy != 0
                y += dy
                ysteps -= abs(dy)
                if ysteps == 0:
                    direction = (direction + 1) & 3
                    dx, dy = deltas[direction]
                    ysteps = steps
34 lines | 1061 bytes | submitted January 4, 2024 | GitHub   6% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 85% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Matrix
  • Simulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation generates the coordinates of a rectangular grid in a spiral order that starts at a given cell. It walks outward layer by layer, alternating right, down, left and up movements while expanding the step length after each horizontal segment. The algorithm stops once every cell of the rows × cols matrix has been visited. The function is written as a generator, yielding each valid coordinate as it is discovered.

Initialization

The code begins by mapping the start column and row to local variables x and y. A list of direction vectors, deltas, encodes the four cardinal moves in the order right, down, left, up. The initial direction index is set to zero, selecting the rightward vector. The step counters steps, xsteps, and ysteps are all initialized to one, meaning the first move will advance a single cell.

x = cStart
y = rStart

deltas = [ [ +1, 0], [ 0, +1 ], [ -1, 0 ], [ 0, -1] ]
direction = 0
dx, dy = deltas[direction]

steps  = 1
xsteps = ysteps = steps

Two bookkeeping variables, found and size, track how many in-bounds cells have been emitted and the total number of cells that must be produced.

found = 0
size  = rows * cols

Main Loop

A while loop runs until found equals size. Inside the loop the current position is examined; if it lies inside the matrix bounds, the coordinate (y, x)-row then column-is yielded and found is incremented.

while found < size:
    if 0 <= x < cols and 0 <= y < rows:
        yield y, x   # row, col
        found += 1

Horizontal Movement

When the active direction has a non-zero dx (right or left), the algorithm updates the column index, decrements the remaining horizontal steps, and checks whether the segment has been exhausted. Upon completion it rotates to the next direction, fetches the new vector, increments the overall step length, and resets the horizontal step counter.

if dx != 0:
    x += dx
    xsteps -= abs(dx)
    if xsteps == 0:
        direction += 1
        dx, dy = deltas[direction]
        steps += 1
        xsteps = steps

Vertical Movement

When dx is zero, the active direction is vertical (down or up). The row index is updated, the vertical step counter is decremented, and on exhaustion the direction index is advanced using a bitwise AND with 3 to wrap around the four entries. The new direction vector is loaded and the vertical step counter is refreshed with the current steps value.

else: # dy != 0
    y += dy
    ysteps -= abs(dy)
    if ysteps == 0:
        direction = (direction + 1) & 3
        dx, dy = deltas[direction]
        ysteps = steps

Edge Cases Handled

The loop’s bound check (0 <= x < cols and 0 <= y < rows) ensures that coordinates falling outside the matrix are simply ignored. This allows the spiral to continue expanding even after it has stepped beyond the grid edges, guaranteeing that all interior cells will eventually be visited regardless of the starting position. The use of abs(dx) and abs(dy) correctly decrements the step counters for both positive and negative moves, so the algorithm works uniformly for leftward and upward steps.

The direction index is wrapped with & 3, a bitwise operation that efficiently maps any integer to the range [0,3]. This prevents an out-of-range list access when the direction counter exceeds the length of deltas.

Performance Optimizations

The implementation relies on a single mutable loop that performs only integer arithmetic and a few array lookups per iteration. By yielding coordinates directly, it avoids allocating an intermediate list of size rows × cols, which reduces memory pressure for large grids. The step counters (xsteps, ysteps) are decremented by abs(dx) or abs(dy), eliminating the need for separate counters for each direction. The bitwise wrap (& 3) is faster than a modulo operation, and the direction vectors are stored as simple two-element lists, enabling quick unpacking into dx and dy. The early exit condition (found < size) stops the loop precisely when the required number of cells has been emitted, preventing unnecessary traversal beyond the matrix boundaries.

written by openai gpt

ELI5 - Simplified Explanation

Imagine standing in the middle of a big grid of square tiles, like a giant game board spread out on the floor. To find every single tile in order, imagine walking in a path that spirals outward, getting wider and wider like the shell of a snail.

The code starts by picking a spot on the board to stand. It keeps track of which direction to walk, starting by moving to the right. Every time it takes a few steps, it turns to the side to make a corner. After turning, it decides to walk even further than before to keep the spiral growing.

As it walks, it checks if it is still inside the boundaries of the board. If the current square is a part of the grid, it remembers that spot and counts it. It keeps doing this over and over again, spiraling bigger and bigger, until it has visited every single square on the whole board. Once the count of visited squares matches the total number of squares on the board, the journey finishes.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 5.85 | σ = 2.03

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ JS Java Go Python TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lzl124631x C++
ruoru Rust
suxrobGM C#
withaarzoo C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lzl124631x C++
ruoru Rust
suxrobGM C#
withaarzoo C++
zfang399 C++
30 links | 16 authors | 8 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

5 solutions   January 4, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality