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     vector<vector<int> > generateMatrix(int n) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.
 4         vector<vector<int>> result(n, vector<int>(n, 0));
 5         if(n == 0)
 6             return result;
 7         int i,j,k=1;
 8         for(i = 0; i < n/2; i++){
 9             for(j = i; j < n-1-i; j++){
10                 result[i][j] = k++;
11             }
12             for(j = i; j < n-1-i; j++){
13                 result[j][n-1-i] = k++;
14             }
15             for(j = n-1-i; j > i; j--){
16                 result[n-1-i][j] = k++;
17             }
18             for(j = n-1-i; j > i; j--){
19                 result[j][i] = k++;
20             }
21         }
22         if(n%2 == 1)
23             result[n/2][n/2] = k;
24         return result;
25     }
原文地址:https://www.cnblogs.com/waruzhi/p/3410881.html