LeetCode spiral-marix2

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。 示例:

输入: 3 输出: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]

解答:

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution {
public:
vector<vector<int>> generateMatrix1(int n) {
vector<vector<int>> matrix(n, vector<int>(n));
int k = 1;
for (int i = 0; i <= n /2; ++i) {
for (int j = i; j < n-i-1; ++j) { matrix[i][j] = k++; }
for (int j = i; j < n-i-1; ++j) { matrix[j][n-i-1] = k++; }
for (int j = n-i-1; j >= i; --j) { matrix[n-i-1][j] = k++; }
for (int j = n-i-2; j > i; --j) { matrix[j][i] = k++; }
}
return matrix;
}

vector<vector<int>> generateMatrix2(int n) {
vector<vector<int>> result(n, vector<int>(n));
int leftX = 0, rightX = n - 1, topY = 0, downY = n - 1;
int count = 1;
while(true) {
for(int x = leftX; x <= rightX; x++)
{
result[topY][x] = count++;
}
if(++topY > downY)
break;

for(int y = topY; y <= downY; y++)
{
result[y][rightX] = count++;
}

if(--rightX < leftX)
break;

for(int x = rightX; x >= leftX; x--)
{
result[downY][x] = count++;
}

if(--downY < topY)
break;

for(int y = downY; y >= topY; y--)
{
result[y][leftX] = count++;
}

if(++leftX > rightX)
break;
}
return result;
}
};

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×