MEDIUM
Spiral Matrix II
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n^2 in spiral order.
Example
Input:
n = 3
Output:
[[1,2,3],[8,9,4],[7,6,5]]
Explanation:
The matrix is filled in spiral order.
Constraints
- 1 ≤ n ≤ 20
Solution: Simulation
- Time Complexity: O(n^2)
- Space Complexity: O(n^2)
C++
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> matrix(n, vector<int>(n));
int num = 1, top = 0, bottom = n - 1, left = 0, right = n - 1;
while (top <= bottom && left <= right) {
for (int j = left; j <= right; ++j) matrix[top][j] = num++;
++top;
for (int i = top; i <= bottom; ++i) matrix[i][right] = num++;
--right;
if (top <= bottom) {
for (int j = right; j >= left; --j) matrix[bottom][j] = num++;
--bottom;
}
if (left <= right) {
for (int i = bottom; i >= top; --i) matrix[i][left] = num++;
++left;
}
}
return matrix;
}
};