-
Notifications
You must be signed in to change notification settings - Fork 257
/
spiral-matrix-ii.cpp
81 lines (75 loc) · 2.3 KB
/
spiral-matrix-ii.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
70
71
72
73
74
75
76
77
78
79
80
81
// Time: O(n^2)
// Space: O(1)
class Solution {
public:
/**
* @param n an integer
* @return a square matrix
*/
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> matrix(n, vector<int>(n));
for (int num = 0, left = 0, right = n - 1, top = 0, bottom = n - 1;
left <= right && top <= bottom;
++left, --right, ++top, --bottom) {
for (int j = left; j <= right; ++j) {
matrix[top][j] = ++num;
}
for (int i = top + 1; i < bottom; ++i) {
matrix[i][right] = ++num;
}
for (int j = right; top < bottom && j >= left; --j) {
matrix[bottom][j] = ++num;
}
for (int i = bottom - 1; left < right && i >= top + 1; --i) {
matrix[i][left] = ++num;
}
}
return matrix;
}
};
// Time: O(n^2)
// Space: O(1)
class Solution2 {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int> > matrix(n, vector<int>(n));
enum Action {RIGHT, DOWN, LEFT, UP};
Action action = RIGHT;
for (int i = 0, j = 0, cnt = 0, total = n * n; cnt < total;) {
matrix[i][j] = ++cnt;
switch (action) {
case RIGHT:
if (j + 1 < n && matrix[i][j + 1] == 0) {
++j;
} else {
action = DOWN, ++i;
}
break;
case DOWN:
if (i + 1 < n && matrix[i + 1][j] == 0) {
++i;
} else {
action = LEFT, --j;
}
break;
case LEFT:
if (j - 1 >= 0 && matrix[i][j - 1] == 0) {
--j;
} else {
action = UP, --i;
}
break;
case UP:
if (i - 1 >= 0 && matrix[i - 1][j] == 0) {
--i;
} else {
action = RIGHT, ++j;
}
break;
default:
break;
}
}
return matrix;
}
};