您的位置:首页 > 其它

【leetcode】Spiral Matrix II

2015-05-03 20:04 429 查看
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 ]
]

class Solution {
public:
vector<vector<int> >generateMatrix(int n) {
int m=0;
vector<vector<int> >a;
a.resize(n,vector<int>(n));
if(n==0)
return a;
int x=0;
int y=0;
m=a[0][0]=1;

while(m<n*n)
{
while(y<n-1&&!a[x][y+1])
{
m++;
y++;
a[x][y]=m;
}
while(x<n-1&&!a[x+1][y])
{
m++;
x++;
a[x][y]=m;
}

while(y-1>=0&&!a[x][y-1])
{
m++;
y--;
a[x][y]=m;
}

while(x-1>=0&&!a[x-1][y])
{
m++;
x--;
a[x][y]=m;
}
}

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