-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlec2_SpiralMatrix.cpp
More file actions
46 lines (38 loc) · 1.42 KB
/
lec2_SpiralMatrix.cpp
File metadata and controls
46 lines (38 loc) · 1.42 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
https://leetcode.com/problems/spiral-matrix/description/
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int top = 0;
int right = matrix[0].size() - 1;
int bottom = matrix.size() - 1;
int left = 0;
vector<int> ans;
while (top <= bottom && left <= right) {
// Traverse from left to right
for (int j = left; j <= right; j++) {
ans.push_back(matrix[top][j]);
}
top++;
// Traverse from top to bottom
for (int i = top; i <= bottom; i++) {
ans.push_back(matrix[i][right]);
}
right--;
// Traverse from right to left (if there are remaining rows)
if (top <= bottom) {
for (int j = right; j >= left; j--) {
ans.push_back(matrix[bottom][j]);
}
bottom--;
}
// Traverse from bottom to top (if there are remaining columns)
if (left <= right) {
for (int i = bottom; i >= top; i--) {
ans.push_back(matrix[i][left]);
}
left++;
}
}
return ans;
}
};