# 59. Spiral Matrix II
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
# Solution
Approach 1: Layer-by-layer.
# Code (Python)
Approach 1:
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
mat = [[0] * n for _ in range(n)]
num = 1
row, col, direction = 0, 0, 0
deltas = {
0: (0, 1),
1: (1, 0),
2: (0, -1),
3: (-1, 0)
}
while num <= n * n:
mat[row][col] = num
if not (0 <= deltas[direction][0] + row < n and 0 <= deltas[direction][1] + col < n and mat[deltas[direction][0] + row][deltas[direction][1] + col] == 0):
direction = (direction + 1) % 4
row, col = deltas[direction][0] + row, deltas[direction][1] + col
num += 1
return mat
# Code (C++)
Approach 1:
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> spiral = vector<vector<int>>(n, vector<int>(n,0));
int head = 0;
int tail = n - 1;
int count = 1;
while (head < tail)
{
for (int col = head; col < tail; ++col)
{
spiral[head][col] = count++;
}
for (int row = head; row < tail; ++row)
{
spiral[row][tail] = count++;
}
for (int col = tail; col > head; --col)
{
spiral[tail][col] = count++;
}
for (int row = tail; row > head; --row)
{
spiral[row][head] = count++;
}
head++;
tail--;
}
if (head == tail)
spiral[head][tail] = count;
return spiral;
}
};