题目链接: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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution
{
public:
vector<vector<int> > generateMatrix(int n)
{
vector<vector<int> > vvi(n, vector<int>(n, 0));
if(n < 1)
return vvi;
int i = 0, j = 0, k = 1;
vvi[i][j] = k;
while(k < n * n)
{
while(j + 1 < n && vvi[i][j + 1]==0)
vvi[i][++ j] = ++ k;
while(i + 1 < n && vvi[i + 1][j]==0)
vvi[++ i][j] = ++ k;
while(j - 1 >= 0 && vvi[i][j - 1]==0)
vvi[i][-- j] = ++ k;
while(i - 1 >= 0 && vvi[i - 1][j]==0)
vvi[-- i][j] = ++ k;
}
return vvi;
}
};
当然,由于这里处理边界问题比较统一,因此也可以将四个方向的移动合并到一起,通过move = [[0, 1], [1, 0], [0, -1], [-1, 0]]数组控制移动。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution
{
public:
vector<vector<int> > generateMatrix(int n)
{
vector<vector<int> > vvi(n, vector<int>(n, 0));
if(n < 1)
return vvi;
int move[4][2] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };
int x = 0, y = 0, k = 1;
vvi[0][0] = k;
while(k < n * n)
for(int i = 0; i < 4; ++ i)
while(x + move[i][0] >= 0 && x + move[i][0] < n &&
y + move[i][1] >= 0 && y + move[i][1] < n &&
vvi[x + move[i][0]][y + move[i][1]] == 0)
vvi[x += move[i][0]][y += move[i][1]] = ++ k;
return vvi;
}
};