Problem 59

Abstract / Summary

Generate a square matrix filled with numbers in spiral order starting from one in the top left corner.

Note

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

C++ 0059.cpp

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {

        if (n == 1)
            return { { 1 }};

        // see problem 54
        vector<vector<int>> result;
        result.resize(n);
        for (auto& r : result)
            r.resize(n, 0);

        int dx = 1;
        int dy = 0;
        int x = 0;
        int y = 0;

        int value = 1;
        while (true)
        {
            if (result[y][x] > 0)
                break;

            result[y][x] = value++;

            x += dx;
            y += dy;

            if (x < 0 || y < 0 || y >= n || x >= n || result[y][x] > 0)
            {
                x -= dx;
                y -= dy;
                if      (dx == +1) { dx = 0; dy = +1; }
                else if (dx == -1) { dx = 0; dy = -1; }
                else if (dy == +1) { dx = -1; dy = 0; }
                else               { dx = +1; dy = 0; }
                x += dx;
                y += dy;
            }
        }

        return result;
    }
};

45 lines | 1057 bytes | submitted August 8, 2023 | GitHub   2% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 76% (1+ million 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 an n x n matrix filled with the integers from 1 to n² in a clockwise spiral order. It follows a procedural approach: allocate the matrix, walk through the cells while maintaining a direction vector, and turn whenever the next step would leave the bounds or encounter an already-filled cell. The algorithm terminates when the next cell to write is already occupied, which indicates that the entire matrix has been populated.

Matrix Allocation

The code begins by handling the trivial case where n equals 1, returning a single-element matrix immediately. For larger sizes it creates a two-dimensional vector and explicitly resizes each row to contain n zeros. This pre-allocation guarantees that every cell is addressable without further dynamic growth.

vector<vector<int>> result;
result.resize(n);
for (auto& r : result)
    r.resize(n, 0);

Direction Management

Movement across the matrix is driven by two integer variables, dx and dy, which together represent the current step direction. The initial direction is set to move right (dx = 1, dy = 0). After each placement the coordinates are updated by adding the direction components.

int dx = 1;
int dy = 0;
int x = 0;
int y = 0;

When the next position would be invalid-either out of bounds or already occupied-the algorithm reverses the last move, rotates the direction clockwise, and then proceeds one step in the new direction. The rotation logic is expressed as a series of conditional assignments that map each cardinal direction to the next one in the clockwise sequence.

if (x < 0 || y < 0 || y >= n || x >= n || result[y][x] > 0)
{
    x -= dx;
    y -= dy;
    if      (dx == +1) { dx = 0; dy = +1; }
    else if (dx == -1) { dx = 0; dy = -1; }
    else if (dy == +1) { dx = -1; dy = 0; }
    else               { dx = +1; dy = 0; }
    x += dx;
    y += dy;
}

Value Insertion Loop

The core of the algorithm is a while (true) loop that continues until a termination condition is met. Inside the loop the current cell is checked; if it already contains a positive value, the loop breaks, signalling completion. Otherwise the current value is written, the counter is incremented, and the coordinates are advanced according to the current direction.

int value = 1;
while (true)
{
    if (result[y][x] > 0)
        break;

    result[y][x] = value++;

    x += dx;
    y += dy;

    // boundary and collision handling follows
}

Edge Cases Handled

The implementation explicitly addresses the smallest possible matrix size (n == 1) by returning a pre-filled 1×1 matrix, avoiding any further processing. During traversal, the condition that checks for out-of-range indices (x < 0 || y < 0 || y >= n || x >= n) prevents illegal memory access. The additional test result[y][x] > 0 ensures that the algorithm does not overwrite cells that have already been assigned, which also serves as the termination trigger when the spiral has closed on itself.

Performance Optimizations

The code minimizes overhead by allocating the full matrix up front, eliminating the need for repeated resizing or push-back operations during the fill phase. Direction changes are performed with simple integer assignments rather than more costly data structures such as lookup tables or enumerations. The loop body contains only a handful of arithmetic and conditional checks, keeping the per-iteration cost low. By using a single contiguous vector<vector<int>> layout, cache locality is improved when accessing rows sequentially during the fill process.

Overall, the solution delivers a clear, deterministic traversal that fills the matrix in linear time relative to the number of cells, while keeping memory usage predictable through upfront allocation.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a shiny empty box made of smaller square tiles. The goal is to fill every single tile with a number, starting from one and counting up as high as possible. To do this, a path is drawn that travels in a spiral, just like a snake winding its way inward toward the middle of the box.

The computer starts at the top left corner and begins walking along the edge. It keeps track of its direction, moving sideways or up and down to follow the spiral shape. Every time the computer steps into a new square, it leaves behind a number. It keeps going until it hits a wall or a space that is already filled with a number. When that happens, the computer stops, turns a corner to change its direction, and keeps moving forward again. It repeats this turn and step pattern over and over until every single square is full and the whole path is complete.

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 | μ = 7.12 | σ = 0.93

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++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Rust JS Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JS
fartem Ruby
fengvyi C++
fpdjsns C++
gaosq0604 Python
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
fartem Ruby
fengvyi C++
fpdjsns C++
gaosq0604 Python
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
YuriSpiridonov Python
zfang399 C++
53 links | 37 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Spiral Matrix II - Leetcode 59 - Python'
NeetCodeIO 17 mins
Spiral Matrix II - Leetcode 59 - Python
YouTube video 'Spiral Matrix II | Leetcode 59 | Matrix | Day-13'
Ayushi Sharma 22 mins
Spiral Matrix II | Leetcode 59 | Matrix | Day-13
YouTube video 'Spiral Matrix II | spiral matrix ii | leetcode 59 | Array'
Naresh Gupta 9 mins
Spiral Matrix II | spiral matrix ii | leetcode 59 | Array
YouTube video '[Java] Leetcode 59. Spiral Matrix II [Array #8]'
Eric Programming 7 mins
[Java] Leetcode 59. Spiral Matrix II [Array #8]
YouTube video 'LeetCode 59: Spiral Matrix II - Interview Prep Ep 32'
Fisher Coder 12 mins
LeetCode 59: Spiral Matrix II - Interview Prep Ep 32
YouTube video 'Leetcode - Spiral Matrix II (Python)'
Timothy H Chang 8 mins
Leetcode - Spiral Matrix II (Python)
YouTube video 'Spiral Matrix II - Standard Technique || Matrix || Arrays || C++/Java/Python || Leetcode 59'
Aryan Mittal 10 mins
Spiral Matrix II - Standard Technique || Matrix || Arrays || C++/Java/Python || Leetcode 59
YouTube video 'Spiral Matrix II | Leetcode 59 | Matrix  2D 🔥🔥 | Live coding session'
Coding Decoded 12 mins
Spiral Matrix II | Leetcode 59 | Matrix 2D 🔥🔥 | Live coding session
YouTube video 'Spiral Matrix II Python Solution - LeetCode #59'
Professor Oakes 7 mins
Spiral Matrix II Python Solution - LeetCode #59
YouTube video '59 || Spiral Matrix II || C++ || Leetcode Daily Challenge'
CodeFreaks 13 mins
59 || Spiral Matrix II || C++ || Leetcode Daily Challenge
YouTube video '59. Spiral Matrix II | JavaScript | Easy solution | LeetCode Daily Challenge'
LeetCodeWithMonu 17 mins
59. Spiral Matrix II | JavaScript | Easy solution | LeetCode Daily Challenge
YouTube video 'Daily Leetcode #743: Apr 13, 2022 - 59. Spiral Matrix II'
Programming Live with Larry 15 mins
Daily Leetcode #743: Apr 13, 2022 - 59. Spiral Matrix II
YouTube video 'Leetcode 59 - Spiral Matrix II (JAVA Solution Explained!)'
LC Bear 10 mins
Leetcode 59 - Spiral Matrix II (JAVA Solution Explained!)
YouTube video 'Daily Leetcode #1135: May 10, 2023 - 59. Spiral Matrix II'
Programming Live with Larry 6 mins
Daily Leetcode #1135: May 10, 2023 - 59. Spiral Matrix II
YouTube video 'Daily Leetcode #251: Dec 07, 2020 - 59. Spiral Matrix II'
Programming Live with Larry 9 mins
Daily Leetcode #251: Dec 07, 2020 - 59. Spiral Matrix II
YouTube video 'Spiral Matrix II - LeetCode 59 - Python Solution'
Code with Carter 12 mins
Spiral Matrix II - LeetCode 59 - Python Solution
YouTube video 'Leetcode Question 59 "Spiral Matrix II" in Javascript'
Ghumman Tech 8 mins
Leetcode Question 59 "Spiral Matrix II" in Javascript
YouTube video 'Leetcode 59: Spiral Matrix II'
Algorithms Casts 20 mins
Leetcode 59: Spiral Matrix II
YouTube video 'leetcode 59. Spiral Matrix II -  rotation matrix method follow up example'
Code-Yao 9 mins
leetcode 59. Spiral Matrix II - rotation matrix method follow up example
YouTube video 'LeetCode: 59. Spiral Matrix II (Visualized)'
Code With Zi 14 mins
LeetCode: 59. Spiral Matrix II (Visualized)
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

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