1 class Solution {
2 public:
3 vector<vector<int> > generateMatrix(int n) {
4 // Note: The Solution object is instantiated only once and is reused by each test case.
5 vector<vector<int> > matrix;
6 if (n<=0)
7 return matrix;
8 int flag[4] = {0, n-1, 0, n-1};
9 int direction = 0; //left 2 right;
10 int i, j;
11 for (i=0; i<n; i++){
12 vector<int> vi;
13 for (j=0; j<n; j++)
14 vi.push_back(1);
15 matrix.push_back(vi);
16 }
17 int t = 1;
18 while (true){
19 j = 2 - 2 * (direction%2); //j=0 or j=2
20 if (flag[j]>flag[j+1])
21 break;
22 int start = flag[j]*(1-direction/2) + flag[j+1]*(direction/2); // start of iteration
23 int delta = 1 - direction/2 - direction/2;
24 for (i=start; i<=flag[j+1] && i>=flag[j]; i+=delta){
25 int rowIndex = i*(direction%2)+ flag[0]*(((direction+3)%4)/3) + flag[1]*(((direction+1)%4)/3);
26 int colIndex = i*(1-direction%2)+flag[3]*(((direction+2)%4)/3) + flag[2]*(direction/3);
27 matrix[rowIndex][colIndex]=t++;
28 }
29 int index = 2*(direction%2) + ((direction+1)%4)/2;
30 flag[index] = flag[index] - ((direction+1)%4)/2 + ((direction+3)%4)/2;
31 direction = (direction+1)%4;
32 }
33 return matrix;
34 }
35 };