-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathleetcode_0059_Spiral_Matrix_II.cpp
More file actions
94 lines (81 loc) · 2.12 KB
/
leetcode_0059_Spiral_Matrix_II.cpp
File metadata and controls
94 lines (81 loc) · 2.12 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* 模拟法
* AC:
* Runtime: 0 ms, faster than 100.00% of C++ online submissions for Spiral Matrix II.
* Memory Usage: 6.5 MB, less than 64.81% of C++ online submissions for Spiral Matrix II.
*
*/
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
if (n == 0) {
return vector<vector<int>> ();
}
vector<vector<int>> ret(n, vector<int>(n, 0));
int direction = 0; // 0 向右,1向下,2向左,3向上
int i = 0, j = 0, now = 1;
while (now <= n * n) {
if (ret[i][j] == 0) {
ret[i][j] = now;
}
bool isExit = false;
switch (direction) {
case 0:
if (j + 1 > n - 1 || ret[i][j + 1] != 0) {
// 转变方向
direction = (direction + 1) % 4;
if (i + 1 > n - 1 || ret[i + 1][j] != 0) {
// 无处转向,退出
isExit = true;
} else {
i++;
break;
}
}
j++;
break;
case 1:
if (i + 1 > n - 1 || ret[i + 1][j] != 0) {
direction = (direction + 1) % 4;
if (j - 1 < 0 || ret[i][j - 1] != 0) {
isExit = true;
} else {
j--;
break;
}
}
i++;
break;
case 2:
if (j - 1 < 0 || ret[i][j - 1] != 0) {
direction = (direction + 1) % 4;
if (i - 1 < 0 || ret[i - 1][j] != 0) {
isExit = true;
} else {
i--;
break;
}
}
j--;
break;
case 3:
if (i - 1 < 0 || ret[i - 1][j] != 0) {
direction = (direction + 1) % 4;
if (j + 1 > n - 1 || ret[i][j + 1] != 0) {
isExit = true;
} else {
j++;
break;
}
}
i--;
break;
}
if (isExit) {
return ret;
}
now++;
}
return ret;
}
};