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 ]
]
与LeetCode之Spiral Matrix 实际上是一样的道理。
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int>> matrix(n, vector<int>(n, 0));
if (n == 0) return matrix;
int rowB = 0, rowE = matrix.size()-1;
int columnB = 0, columnE = matrix[0].size()-1;
int value=1;
while(true){
//left->right
for (int i = columnB; i <= columnE; i++)
matrix[rowB][i]=value++;
if (++rowB > rowE)
break;
//top->bottom
for (int i = rowB; i <= rowE; i++)
matrix[i][columnE]=value++;
if (--columnE < columnB)
break;
//right->left
for (int i = columnE; i >= columnB; i--)
matrix[rowE][i]=value++;
if (--rowE < rowB)
break;
//bottom->top
for (int i = rowE; i >= rowB; i--)
matrix[i][columnB]=value++;
if (++columnB > columnE)
break;
}//while
return matrix;
}
};