leetocde 59. Spiral Matrix II (模拟)

Given an integer n, generate a square matrix filled with elements from 1 to _n_2 in spiral order.

思路:仿佛回到高一的那个暑假。。。

1/* ***********************************************
2Author :111qqz
3Created Time :2017年04月11日 星期二 18时52分15秒
4File Name :59.cpp
5************************************************ */
6class Solution {
public:
 1    int ok (int dir, int &x,int &y,int n,vector<vector<int> >&res)  // 0右,1下,2左,3上
 2    {
 3	if (dir==0)
 4	{
 5	    if (y<=n-2&&res[x][y+1]==0) y++;
 6	    else
 7	    {
 8		dir++;
 9		x++;
10	    }
11	    return dir;
12	}
13	if (dir==1)
14	{
15	    if (x<=n-2&&res[x+1][y]==0) x++;
16	    else
17	    {
18		dir++;
19		y--;
20	    }
21	    return dir;
22	}
23	if (dir==2)
24	{
25	    if (y>=1&&res[x][y-1]==0) y--;
26	    else
27	    {
28		dir++;
29		x--;
30	    }
31	    return dir;
32	}
33	if (dir==3)
34	{
35	    if (x>=1&&res[x-1][y]==0) x--;
36	    else
37	    {
38		dir = 0 ;
39		y++;
40	    }
41	    return dir;
42	}
43    }
    vector<vector<int>> generateMatrix(int n) {
 1	vector<vector<int> >res(n,vector<int>(n,0));
 2	int dir = 0;
 3	int x,y;
 4	x = y = 0 ;
 5	for ( int i = 0 ; i < n*n ; i++)
 6	{
 7	    res[x][y] = i+1;
 8//	    printf(" x:%d y: %d\n",x,y);
 9	    dir = ok (dir,x,y,n,res);
10	}
11	return res;
    }

};