Leetcode 59. Spiral Matrix II (Medium) (cpp)
Tag: Array
Difficulty: Medium
/*
59. Spiral Matrix II (Medium)
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
*/
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
if (n < 1) {
return {};
}
vector<vector<int>> res(n, vector<int>(n));
int i = n - 1, j = n - 1, k = 1, h = 0, l = 0;
while (k <= n * n) {
for (int col = l; col <= j; col++) {
res[h][col] = k++;
}
if (++h > i) {
break;
}
for (int row = h; row <= i; row++) {
res[row][j] = k++;
}
if (--j < l) {
break;
}
for (int col = j; col >= l; col--) {
res[i][col] = k++;
}
if (--i < h) {
break;
}
for (int row = i; row >= h; row--) {
res[row][l] = k++;
}
if (++l > j) {
break;
}
}
return res;
}
};