-
Notifications
You must be signed in to change notification settings - Fork 0
/
螺旋矩阵 II (generateMatrix).cpp
69 lines (61 loc) · 1.22 KB
/
螺旋矩阵 II (generateMatrix).cpp
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
**和螺旋矩阵1类似,只是把遍历变成了生成矩阵,思路相同,参考上题
*/
#include <string>
#include <sstream>
#include <algorithm>
#include <stack>
#include <cmath>
#include <iostream>
#include <vector>
#include <set>
using namespace std;
vector<vector<int>> generateMatrix(int n) {
int count = 1;
int row = n;
int col = n;
vector<int> temp(col, 0);
vector<vector<int>> ma(row, temp);
vector<vector<int>> rel(row, temp);
if (n == 1) {
rel[0][0] = 1;
return rel;
}
int i = 0;
int j = 0;
int circle = 0;
int flag = 0;
while (ma[i][j] == 0) {
rel[i][j] = count;
ma[i][j] = 1;
count++;
if (i == circle) {
if (j < (col - 1 - circle)) flag = 1;
if (j == (col - 1 - circle)) flag = 2;
}
else if (i == (row - 1 - circle)) {
if (j > circle) flag = 3;
if (j == circle) flag = 4;
}
else if (j == (col - 1 - circle)) flag = 5;
else if (i == (circle + 1)) flag = 6;
else flag = 7;
switch (flag) {
case 1: j++; break;
case 2: i++; break;
case 3: j--; break;
case 4: i--; break;
case 5: i++; break;
case 6: j++; circle++; break;
case 7: i--; break;
default: break;
}
}
return rel;
}
int main() {
int n = 3;
generateMatrix(n);
system("pause");
return 0;
}