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 - Direction Simulation INPUT Given: n = 3 Empty 3x3 Matrix: ? ? ? ? ? ? ? ? ? Fill with: 1 to 9 [1, 2, 3, 4, 5, 6, 7, 8, 9] ALGORITHM STEPS 1 Initialize Directions Right, Down, Left, Up R:(0,1) D:(1,0) L:(0,-1) U:(-1,0) 2 Start at (0,0) Begin moving Right 3 Fill & Move Place num, advance 4 Turn on Boundary Change direction clockwise FINAL RESULT Filled Spiral Matrix: 1 2 3 8 9 4 7 6 5 Output Array: [[1,2,3], [8,9,4], [7,6,5]] OK - Verified Key Insight: Use direction vectors (dr, dc) to simulate spiral movement. When hitting a boundary or visited cell, rotate clockwise by changing direction index: dir = (dir + 1) % 4. Time: O(n²) | Space: O(n²) for the result matrix TutorialsPoint - Spiral Matrix II | Direction Simulation Approach
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