-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path54.cpp
78 lines (61 loc) · 1.5 KB
/
54.cpp
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
78
#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> result;
int m = matrix.size();
int n = matrix[0].size();
if( m == 0 || n == 0)
return result;
int count = 1;
int i = 0 ;
int j = 0 ;
int row = 0;
int span = n;
while (count <= m*n)
{
i = row;
j = row;
// left to right
for(;j<=row+span-1;j++)
{
result.push_back(matrix[i][j]);
count++;
}
j--;
// down
for(++i;i<=row+span-1;i++)
{
result.push_back(matrix[i][j]);
count++;
}
i--;
// right to left
for(--j;j>=row;j--)
{
result.push_back(matrix[i][j]);
count++;
}
j++;
// up
for(--i;i>=row+1;i--)
{
result.push_back(matrix[i][j]);
count++;
}
row++;
span -= 2;
}
return result;
}
};
int main()
{
Solution sol = new Solution();
vector<vector<int>> matrix;
matrix = {};
cout<< sol.spiralOrder(matrix)<<endl;
return 0;
}