forked from cpselvis/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution054.cpp
More file actions
77 lines (65 loc) · 1.29 KB
/
solution054.cpp
File metadata and controls
77 lines (65 loc) · 1.29 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Spiral Matrix
*
* cpselvis([email protected])
* September 20th, 2016
*/
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> >& matrix) {
vector<int> ret;
if (matrix.size() == 0)
{
return ret;
}
int rowBegin = 0, rowEnd = matrix.size() - 1;
int colBegin = 0, colEnd = matrix[0].size() - 1;
while (rowBegin <= rowEnd && colBegin <= colEnd)
{
for (int i = colBegin; i <= colEnd; i ++)
{
ret.push_back(matrix[rowBegin][i]);
}
rowBegin ++;
for (int i = rowBegin; i <= rowEnd; i ++)
{
ret.push_back(matrix[i][colEnd]);
}
colEnd --;
if (rowBegin <= rowEnd)
{
for (int i = colEnd; i >= colBegin; i --)
{
ret.push_back(matrix[rowEnd][i]);
}
rowEnd --;
}
if (colBegin <= colEnd)
{
for (int i = rowEnd; i >= rowBegin; i --)
{
ret.push_back(matrix[i][colBegin]);
}
colBegin ++;
}
}
return ret;
}
};
int main(int argc, char **argv)
{
vector<vector<int> > vec({
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
});
Solution s;
vector<int> ret = s.spiralOrder(vec);
for (auto i : ret)
{
cout << i << endl;
}
}