https://oj.leetcode.com/problems/spiral-matrix-ii/
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> matrix(n, vector<int>(n));
int maxNum = n * n;
int currentNum = 1;
int columnBegin = 0;
int rowBegin = 0;
int columnEnd = n - 1;
int rowEnd = n - 1;
while (currentNum <= maxNum) {
for (int column = columnBegin; column <= columnEnd; column++) {
matrix[rowBegin][column] = currentNum++;
}
rowBegin++;
for (int row = rowBegin; row <= rowEnd; row++) {
matrix[row][columnEnd] = currentNum++;
}
columnEnd--;
for (int column = columnEnd; column >= columnBegin; column--) {
matrix[rowEnd][column] = currentNum++;
}
rowEnd--;
for (int row = rowEnd; row >= rowBegin; row--) {
matrix[row][columnBegin] = currentNum++;
}
columnBegin++;
}
return matrix;
}
};