题目链接:Spiral Matrix II

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

For example,

Given n = 3,

You should return the following matrix:

[ 
 [ 1, 2, 3 ], 
 [ 8, 9, 4 ], 
 [ 7, 6, 5 ] 
] 

这道题的要求是返回长宽均为n的矩阵,其元素是按照1~n^2的螺旋顺序排列。

Spiral Matrix同样简单的数组操作问题,只需要按右、下、左、上的顺序逐行或列遍历数组。不过在处理边界问题上,这题貌似更容易一些:可以先初始化二维数组均为0,然后填写的时候碰到非0值的时候就改变方向即可。

时间复杂度:O(n2)

空间复杂度:O(n2)

 1 class Solution 
 2 {
 3 public:
 4     vector<vector<int> > generateMatrix(int n)
 5     {
 6         vector<vector<int> > vvi(n, vector<int>(n, 0));
 7         
 8         if(n < 1)
 9             return vvi;
10         
11         int i = 0, j = 0, k = 1;
12         vvi[i][j] = k;
13         while(k < n * n)
14         {
15             while(j + 1 < n && vvi[i][j + 1]==0)
16                 vvi[i][++ j] = ++ k;
17             
18             while(i + 1 < n && vvi[i + 1][j]==0)
19                 vvi[++ i][j] = ++ k;
20             
21             while(j - 1 >= 0 && vvi[i][j - 1]==0)
22                 vvi[i][-- j] = ++ k;
23             
24             while(i - 1 >= 0 && vvi[i - 1][j]==0)
25                 vvi[-- i][j] = ++ k;
26         }
27         
28         return vvi;
29     }
30 };

当然,由于这里处理边界问题比较统一,因此也可以将四个方向的移动合并到一起,通过move = [[0, 1], [1, 0], [0, -1], [-1, 0]]数组控制移动。

 1 class Solution
 2 {
 3 public:
 4     vector<vector<int> > generateMatrix(int n)
 5     {
 6         vector<vector<int> > vvi(n, vector<int>(n, 0));
 7         
 8         if(n < 1)
 9             return vvi;
10         
11         int move[4][2] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };
12         
13         int x = 0, y = 0, k = 1;
14         vvi[0][0] = k;
15         while(k < n * n)
16             for(int i = 0; i < 4; ++ i)
17                 while(x + move[i][0] >= 0 && x + move[i][0] < n &&
18                       y + move[i][1] >= 0 && y + move[i][1] < n &&
19                       vvi[x + move[i][0]][y + move[i][1]] == 0)
20                     vvi[x += move[i][0]][y += move[i][1]] = ++ k;
21         
22         return vvi;
23     }
24 };