-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiralMatrix.cpp
More file actions
41 lines (36 loc) · 1.14 KB
/
SpiralMatrix.cpp
File metadata and controls
41 lines (36 loc) · 1.14 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
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if (matrix.empty() || matrix[0].empty())
return res;
int m = matrix.size();
int n = matrix[0].size();
int rowBegin = 0;
int rowEnd = m - 1;
int colBegin = 0;
int colEnd = n - 1;
while (rowBegin <= rowEnd && colBegin <= colEnd)
{
for (int i = colBegin; i <= colEnd; i++)
res.push_back(matrix[rowBegin][i]);
rowBegin++;
if (rowBegin > rowEnd)
break;
for (int i = rowBegin; i <= rowEnd; i++)
res.push_back(matrix[i][colEnd]);
colEnd--;
if (colBegin > colEnd)
break;
for (int i = colEnd; i >= colBegin; i--)
res.push_back(matrix[rowEnd][i]);
rowEnd--;
if (rowBegin > rowEnd)
break;
for (int i = rowEnd; i >= rowBegin && rowBegin <= rowEnd; i--)
res.push_back(matrix[i][colBegin]);
colBegin++;
}
return res;
}
};