题目:
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 ]
]
题意:
给定一个数字,生成一个n*n的数组,让1到n* n的数字按照顺时针存放。
以上。
代码如下:
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
if(n==0)return vector<vector<int> >();
vector<vector<int> >result(n, vector<int>(n,0));
int square = n * n;
int num = 1;
int x = 0, y = 0;
while(num <= square) {
while(y < n && result[x][y] == 0) {
result[x][y] = num;
y++;
num++;
}
y--;
x++;
while(x < n && result[x][y] == 0) {
result[x][y] = num;
x++;
num++;
}
x--;
y--;
while(y >= 0 && result[x][y] == 0) {
result[x][y] = num;
y--;
num++;
}
x--;
y++;
while(x >= 0 && result[x][y] == 0 ) {
result[x][y] = num;
x--;
num++;
}
x++;
y++;
}
return result;
}
};