Given an integer (n), generate a square matrix filled with elements from 1 to (n^2) in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
思路完全同 54. Spiral Matrix(中等).
自个代码:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> A(n, vector<int>(n)); //n行n列,动态的
// Normal Case
int rowStart = 0;
int rowEnd = n - 1;
int colStart = 0;
int colEnd = n - 1;
int num = 1; //change
while (rowStart <= rowEnd && colStart <= colEnd) {
for (int i = colStart; i <= colEnd; i++) {
A[rowStart][i] = num++; //change
}
rowStart++;
for (int i = rowStart; i <= rowEnd; i++) {
A[i][colEnd] = num++; //change
}
colEnd--;
for (int i = colEnd; i >= colStart; i--) {
if (rowStart <= rowEnd)
A[rowEnd][i] = num++; //change
}
rowEnd--;
for (int i = rowEnd; i >= rowStart; i--) {
if (colStart <= colEnd)
A[i][colStart] = num++; //change
}
colStart++;
}
return A;
}