Back to problems Sign in to unlock
Leetcode
Medium
Arrays
Matrices
Simulation
Google
Spiral Matrix II
Generate an matrix filled with numbers from 1 to in spiral order.
Acceptance 0%
Problem Statement
Problem
Given a positive integer , create an matrix and fill it with the integers from 1 to n^2 in clockwise spiral order, starting from the top-left cell and moving right first.
You should return the completed matrix after all numbers have been placed.
Notes
- The spiral proceeds around the outer layer first, then continues inward.
- Each number from
1ton^2must appear exactly once. - When the spiral reaches the center, it should stop after placing the final value.
Input Format
- A single integer
n.
Interpretation
- Build an
n x ngrid. - Fill cells with
1, 2, 3, ..., n^2in clockwise spiral order.
Output Format
- Return an
n x n2D integer array representing the filled spiral matrix.
Constraints
- .
- The matrix size is .
- Every value from
1ton^2appears exactly once.
Examples
Sample cases returned by the problem API.
Example 1
Input
n = 3
Output
[[1,2,3],[8,9,4],[7,6,5]]
Explanation
The numbers are placed in clockwise spiral order starting from the top-left corner.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.
Guided hints
Editorial and discussion links
Concept map and variants
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.