leetcode59 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 ]
]
 1 class Solution {
 2 public:
 3     vector<vector<int>> generateMatrix(int n) {
 4         vector<vector<int> > ans;
 5         
 6         if(n<=0)
 7             return ans;
 8         
 9         vector<int> temp(n,0);
10         for(int i=0;i<n;i++)
11         {
12             ans.push_back(temp);
13         }
14         
15         int xmin=0,ymin=0,xmax=n-1,ymax=n-1;
16         
17         int total=n*n;
18         
19         ans[0][0]=1;
20         int dir=1;
21         int x=0,y=0;
22         int count=1;
23         
24         while(count<total)
25         {
26             if(dir==1)
27             {
28                if(y+1>ymax)
29                {
30                    xmin++;
31                    dir=2;
32                }
33                else
34                {
35                    y++;
36                    count++;
37                    ans[x][y]=count;
38                }
39             }
40             else if(dir==2)
41             {
42                if(x+1>xmax)
43                {
44                    ymax--;
45                    dir=3;
46                }
47                else
48                {
49                    x++;
50                    count++;
51                    ans[x][y]=count;
52                }
53             }
54             else if(dir==3)
55             {
56                if(y-1<ymin)
57                {
58                    xmax--;
59                    dir=4;
60                }
61                else
62                {
63                    y--;
64                    count++;
65                    ans[x][y]=count;
66                }
67             }
68             else
69             {
70                if(x-1<xmin)
71                {
72                    ymin++;
73                    dir=1;
74                }
75                else
76                {
77                    x--;
78                    count++;
79                    ans[x][y]=count;
80                }
81             }
82         }
83         return ans;
84     }
85 };
View Code
原文地址:https://www.cnblogs.com/jsir2016bky/p/5105861.html