Skip to content

Commit f1e3ee2

Browse files
committed
3
1 parent 08e575c commit f1e3ee2

File tree

1 file changed

+24
-29
lines changed

1 file changed

+24
-29
lines changed

SpiralMatrixII/SpiralMatrixII.cpp

+24-29
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,39 @@
1-
2-
const int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0}; // right, down, left, up
3-
41
class Solution {
52
public:
63
vector<vector<int> > generateMatrix(int n) {
7-
// Start typing your C/C++ solution below
8-
// DO NOT write int main() function
9-
10-
if (n == 0) return vector<vector<int>>();
11-
124
vector<vector<int>> matrix(n, vector<int>(n, 0));
13-
14-
int x = 0, y = -1;
15-
int row = n, col = n + 1;
16-
bool go_horizon = true;
17-
int i = 1, k = 0;
18-
while (i <= n * n) {
5+
int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
6+
int x = 0;
7+
int y = -1;
8+
int k = 0;
9+
int count = 0;
10+
int horizon = true;
11+
int row = n;
12+
int col = n + 1;
13+
while (count < n * n) {
1914
int dx = dir[k%4][0];
2015
int dy = dir[k%4][1];
21-
k += 1;
22-
23-
if (go_horizon) {
24-
go_horizon = false;
25-
col -= 1;
26-
for (int j = 0; j < col; j++, i++) {
16+
k++;
17+
if (horizon) {
18+
horizon = false;
19+
col--;
20+
for (int i = 0; i < col; i++) {
2721
x += dx;
2822
y += dy;
29-
matrix[x][y] = i;
23+
count++;
24+
matrix[x][y] = count;
3025
}
31-
}
32-
else {
33-
go_horizon = true;
34-
row -= 1;
35-
for (int j = 0; j < row; j++, i++) {
26+
} else {
27+
horizon = true;
28+
row--;
29+
for (int i = 0; i < row; i++) {
3630
x += dx;
3731
y += dy;
38-
matrix[x][y] = i;
32+
count++;
33+
matrix[x][y] = count;
3934
}
4035
}
4136
}
42-
return move(matrix);
37+
return matrix;
4338
}
44-
};
39+
};

0 commit comments

Comments
 (0)