您的位置:首页 > 其它

【leetcode】Spiral Matrix II

2015-01-08 20:25 381 查看

Spiral Matrix II

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 ]
]


与Spiral Matrix类似:

class Solution {
public:
vector<vector<int> > generateMatrix(int n) {

int x1=0;
int y1=0;
int x2=n-1;
int y2=n-1;

int count=0;
vector<vector<int>> result(n,vector<int>(n));
while(count<n*n)
{

for(int j=y1;j<=y2;j++)
{
count++;
result[x1][j]=count;
}
for(int i=x1+1;i<=x2;i++)
{
count++;
result[i][y2]=count;
}

for(int j=y2-1;j>=y1;j--)
{
count++;
result[x2][j]=count;
}

for(int i=x2-1;i>x1;i--)
{
count++;
result[i][x1]=count;
}

x1++;y1++;x2--;y2--;
}

return result;

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