-
Notifications
You must be signed in to change notification settings - Fork 0
/
54-SpiralMatrix.cpp
71 lines (68 loc) · 2.3 KB
/
54-SpiralMatrix.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
/*=============================================================================
# FileName: 54-SpiralMatrix.cpp
# Desc: AC, 4ms
# Author: Jian Huang
# Email: [email protected]
# HomePage: https://cn.linkedin.com/in/huangjian1993
# Version: 0.0.1
# LastChange: 2015-08-08 13:18:13
# History:
=============================================================================*/
#include <leetcode.h>
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> >& matrix) {
vector<int> result;
if (matrix.empty()) {
return result;
}
int m = matrix.size(), n = matrix[0].size();
int left = 0, right = n - 1, top = 0, bottom = m - 1;
while (left <= right && top <= bottom) {
if (left == right) {
for (int i = top; i <= bottom; i ++) {
result.push_back(matrix[i][left]);
}
break;
}
if (top == bottom) {
for (int i = left; i <= right; i ++) {
result.push_back(matrix[top][i]);
}
break;
}
for (int i = left; i < right; i ++) {
result.push_back(matrix[top][i]);
}
for (int i = top; i < bottom; i ++) {
result.push_back(matrix[i][right]);
}
for (int i = right; i > left; i --) {
result.push_back(matrix[bottom][i]);
}
for (int i = bottom; i > top; i --) {
result.push_back(matrix[i][left]);
}
left ++;
right --;
top ++;
bottom --;
}
return result;
}
};
int main() {
int size = 3;
vector<vector<int> > matrix(size, vector<int>(size, -1));
for (int i = 0; i < size; i ++) {
for (int j = 0; j < size; j ++) {
matrix[i][j] = i * size + j + 1;
}
}
Solution solution;
vector<int> result = solution.spiralOrder(matrix);
for (int i = 0; i < (int) result.size(); i ++) {
cout << result[i] << " ";
}
cout << endl;
}