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 {
7
8public:
9
10
11 int ok (int dir, int &x,int &y,int n,vector<vector<int> >&res) // 0右,1下,2左,3上
12 {
13 if (dir==0)
14 {
15 if (y<=n-2&&res[x][y+1]==0) y++;
16 else
17 {
18 dir++;
19 x++;
20 }
21 return dir;
22 }
23 if (dir==1)
24 {
25 if (x<=n-2&&res[x+1][y]==0) x++;
26 else
27 {
28 dir++;
29 y--;
30 }
31 return dir;
32 }
33 if (dir==2)
34 {
35 if (y>=1&&res[x][y-1]==0) y--;
36 else
37 {
38 dir++;
39 x--;
40 }
41 return dir;
42 }
43 if (dir==3)
44 {
45 if (x>=1&&res[x-1][y]==0) x--;
46 else
47 {
48 dir = 0 ;
49 y++;
50 }
51 return dir;
52 }
53 }
54
55
56
57
58 vector<vector<int>> generateMatrix(int n) {
59
60 vector<vector<int> >res(n,vector<int>(n,0));
61 int dir = 0;
62 int x,y;
63 x = y = 0 ;
64 for ( int i = 0 ; i < n*n ; i++)
65 {
66 res[x][y] = i+1;
67// printf(" x:%d y: %d\n",x,y);
68 dir = ok (dir,x,y,n,res);
69 }
70 return res;
71
72
73 }
74
75};