https://leetcode.com/problems/spiral-matrix-ii/description/
Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 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]]
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> matrix(n, vector<int>(n));
if (n <= 0)
return matrix;
int u = 0, d = n - 1, l = 0, r = n - 1, k = 1;
while (true) {
// up
for (int col = l; col <= r; col++) matrix[u][col] = k++;
if (++u > d) break;
// right
for (int row = u; row <= d; row++) matrix[row][r] = k++;
if (--r < l) break;
// down
for (int col = r; col >= l; col--) matrix[d][col] = k++;
if (--d < u) break;
// left
for (int row = d; row >= u; row--) matrix[row][l] = k++;
if (++l > r) break;
}
return matrix;
}
};