-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoptimized.cpp
More file actions
35 lines (34 loc) · 970 Bytes
/
Copy pathoptimized.cpp
File metadata and controls
35 lines (34 loc) · 970 Bytes
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
#include "spiral_matrix.hpp"
std::vector<int> Solution::spiralOrder(std::vector<std::vector<int>>& matrix) {
std::vector<int> spiral;
spiral.reserve(matrix.size() * matrix[0].size());
int up = 0, down = matrix.size() - 1;
int left = 0, right = matrix[0].size() - 1;
while (true) {
for (int i = left; i <= right; ++i) {
spiral.push_back(matrix[up][i]);
}
if (++up > down) {
break ;
}
for (int i = up; i <= down; ++i) {
spiral.push_back(matrix[i][right]);
}
if (left > --right) {
break ;
}
for (int i = right; i >= left; --i) {
spiral.push_back(matrix[down][i]);
}
if (up > --down) {
break ;
}
for (int i = down; i >= up; --i) {
spiral.push_back(matrix[i][left]);
}
if (++left > right) {
break ;
}
}
return spiral;
}