您的位置:首页 > 其它

leetcode59 Spiral Matrix II

2016-01-06 15:42 148 查看
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 ]
]


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

if(n<=0)
return ans;

vector<int> temp(n,0);
for(int i=0;i<n;i++)
{
ans.push_back(temp);
}

int xmin=0,ymin=0,xmax=n-1,ymax=n-1;

int total=n*n;

ans[0][0]=1;
int dir=1;
int x=0,y=0;
int count=1;

while(count<total)
{
if(dir==1)
{
if(y+1>ymax)
{
xmin++;
dir=2;
}
else
{
y++;
count++;
ans[x][y]=count;
}
}
else if(dir==2)
{
if(x+1>xmax)
{
ymax--;
dir=3;
}
else
{
x++;
count++;
ans[x][y]=count;
}
}
else if(dir==3)
{
if(y-1<ymin)
{
xmax--;
dir=4;
}
else
{
y--;
count++;
ans[x][y]=count;
}
}
else
{
if(x-1<xmin)
{
ymin++;
dir=1;
}
else
{
x--;
count++;
ans[x][y]=count;
}
}
}
return ans;
}
};


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