Spiral Matrix II
LeetCode 59 | Difficulty: Mediumβ
MediumProblem Descriptionβ
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n^2 in spiral order.
Example 1:

Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]
Example 2:
Input: n = 1
Output: [[1]]
Constraints:
- `1 <= n <= 20`
Topics: Array, Matrix, Simulation
Approachβ
Matrixβ
Treat the matrix as a 2D grid. Common techniques: directional arrays (dx, dy) for movement, BFS/DFS for connected regions, in-place marking for visited cells, boundary traversal for spiral patterns.
When to use
Grid traversal, island problems, path finding, rotating/transforming matrices.
Solutionsβ
Solution 1: C# (Best: 40 ms)β
| Metric | Value |
|---|---|
| Runtime | 40 ms |
| Memory | N/A |
| Date | 2018-04-08 |
Solution
public class Solution {
public int[,] GenerateMatrix(int n) {
int[,] result = new int[n, n];
int k = 0, l = 0, last_row = n-1, last_col = n - 1;
int currentValue = 1;
while (k <= last_row && l <= last_col)
{
for (int i = l; i <= last_col; i++)
{
result[k, i] = currentValue++;
}
k++;
for (int i = k; i <= last_row; i++)
{
result[i, last_col] = currentValue++;
}
last_col--;
if (k <= last_row)
{
for (int i = last_col; i >= l; i--)
{
result[last_row, i] = currentValue++;
}
}
last_row--;
if (l <= last_col)
{
for (int i = last_row; i >= k; i--)
{
result[i, l] = currentValue++;
}
}
l++;
}
return result;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Solution | $O(n)$ | $O(1) to O(n)$ |
Interview Tipsβ
Key Points
- Discuss the brute force approach first, then optimize. Explain your thought process.