-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerateMatrix.cpp
More file actions
51 lines (46 loc) · 1.16 KB
/
generateMatrix.cpp
File metadata and controls
51 lines (46 loc) · 1.16 KB
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
#include <vector>
using namespace std;
class Solution
{
public:
vector<vector<int>> generateMatrix(int n)
{
if (n <= 0) return vector<vector<int>>();
// 这是一个拥有n²个元素,n行n列的矩阵
int left = 0;
int right = n - 1;
int up = 0;
int down = n - 1;
// 扩容!
vector<vector<int>> res(n,vector<int>(n));
int currentValue = 1;
while (currentValue <= n*n)
{
for (int i = left;i <= right;i++)
{
res[up][i] = currentValue;
currentValue++;
}
up++;
for (int i = up;i <= down;i++)
{
res[i][right] = currentValue;
currentValue++;
}
right--;
for (int i = right;i >= left;i--)
{
res[down][i] = currentValue;
currentValue++;
}
down--;
for (int i = down;i >= up;i--)
{
res[i][left] = currentValue;
currentValue++;
}
left++;
}
return res;
}
};