-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path54. Spiral Matrix.cpp
More file actions
46 lines (44 loc) · 1.15 KB
/
54. Spiral Matrix.cpp
File metadata and controls
46 lines (44 loc) · 1.15 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
class Solution
{
public:
vector<int> spiralOrder(vector<vector<int>> &matrix)
{
vector<int> ans;
int rows = matrix.size();
int cols = matrix[0].size();
int total = rows * cols;
int rst = 0;
int rend = rows - 1;
int cst = 0;
int cend = cols - 1;
int cnt = 0;
while (cnt < total)
{
for (int i = cst; i <= cend && cnt < total; i++)
{
ans.push_back(matrix[rst][i]);
cnt++;
}
rst++;
for (int i = rst; i <= rend && cnt < total; i++)
{
ans.push_back(matrix[i][cend]);
cnt++;
}
cend--;
for (int i = cend; i >= cst && cnt < total; i--)
{
ans.push_back(matrix[rend][i]);
cnt++;
}
rend--;
for (int i = rend; i >= rst && cnt < total; i--)
{
ans.push_back(matrix[i][cst]);
cnt++;
}
cst++;
}
return ans;
}
};