您的位置:首页 > 其它

[leetcode] 59.Spiral Matrix II

2015-08-26 23:14 459 查看
题目:

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: