8000 3 · javasharper/leetcode@d049142 · GitHub
[go: up one dir, main page]

Skip to content

Commit d049142

Browse files
committed
3
1 parent f55a27d commit d049142

File tree

1 file changed

+27
-32
lines changed

1 file changed

+27
-32
lines changed

SpiralMatrix/SpiralMatrix.cpp

Lines changed: 27 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,41 @@
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:
6-
vector<int> spiralOrder(vector<vector<int> > &matrix) {
7-
// Start typing your C/C++ solution below
8-
// DO NOT write int main() function
9-
10-
int M = matrix.size();
11-
if (M == 0) return vector<int>();
12-
int N = matrix[0].size();
13-
if (N == 0) return vector<int>();
14-
15-
vector<int> result(M * N, 0);
16-
int x = 0, y = -1;
17-
int row = M, col = N + 1;
18-
bool go_horizon = true;
19-
int i = 0, k = 0;
20-
while (i < M * N) {
3+
vector<int> spiralOrder(vector<vector<int> > &matrix) {
4+
vector<int> result;
5+
if (matrix.empty()) {
6+
return result;
7+
}
8+
int row = matrix.size();
9+
int col = matrix[0].size() + 1;
10+
int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
11+
int x = 0;
12+
int y = -1;
13+
int k = 0;
14+
int count = 0;
15+
bool horizon = true;
16+
while (count < matrix.size() * matrix[0].size()) {
2117
int dx = dir[k%4][0];
2218
int dy = dir[k%4][1];
23-
k += 1;
19+
k++;
2420

25-
if (go_horizon) {
26-
go_horizon = false;
27-
col -= 1;
28-
for (int j = 0; j < col; j++, i++) {
21+
if (horizon) {
22+
horizon = false;
23+
col--;
24+
for (int i = 0; i < col; i++, count++) {
2925
x += dx;
3026
y += dy;
31-
result[i] = matrix[x][y];
27+
result.push_back(matrix[x][y]);
3228
}
33-
}
34-
else {
35-
go_horizon = true;
36-
row -= 1;
37-
for (int j = 0; j < row; j++, i++) {
29+
} else {
30+
horizon = true;
31+
row--;
32+
for (int i = 0; i < row; i++, count++) {
3833
x += dx;
3934
y += dy;
40-
result[i] = matrix[x][y];
35+
result.push_back(matrix[x][y]);
4136
}
4237
}
4338
}
4439
return result;
45-
}
46-
};
40+
}
41+
};

0 commit comments

Comments
 (0)
0