Spiral Matrix II - Problem

Given a positive integer n, generate an n x n matrix filled with elements from 1 to in spiral order.

The spiral order means starting from the top-left corner, moving right across the first row, then down the last column, then left across the bottom row, then up the first column, and repeating this pattern inward until all cells are filled.

Input & Output

Example 1 — Basic 3x3 Matrix
$ Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
💡 Note: Start from top-left, move right (1,2,3), then down (4,5), then left (6,7), then up (8), then to center (9)
Example 2 — Single Element
$ Input: n = 1
Output: [[1]]
💡 Note: Only one cell, so matrix contains just [1]
Example 3 — Even Size Matrix
$ Input: n = 4
Output: [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]
💡 Note: 4x4 matrix filled in spiral order: outer ring (1-12), then inner ring (13-16)

Constraints

  • 1 ≤ n ≤ 20

Visualization

Tap to expand
Spiral Matrix II: Generate n×n Matrix in Spiral OrderInput: n = 33Spiral MovementOutput: Spiral Matrix123894765Fill pattern: Right (1,2,3) → Down (4,5) → Left (6,7) → Up (8) → Center (9)Result: [[1,2,3],[8,9,4],[7,6,5]]
Understanding the Visualization
1
Input
Given integer n=3, create 3×3 matrix
2
Process
Fill matrix in spiral order: right→down→left→up
3
Output
Matrix with numbers 1-9 in spiral pattern
Key Takeaway
🎯 Key Insight: Track four boundaries and shrink them as each side is completed in the spiral
Asked in
Microsoft 35 Amazon 28 Facebook 22 Google 18
125.0K Views
Medium Frequency
~15 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen