-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.cpp
59 lines (52 loc) · 1.51 KB
/
Solution.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
#include <algorithm>
#include <climits>
#include <functional>
#include <iostream>
#include <queue>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int rows = matrix.size();
int cols = matrix[0].size();
vector<int> result;
result.reserve(rows * cols);
// Define the boundaries. To stop traversing when the bounds are reached
int top = 0, bottom = rows - 1, left = 0, right = cols - 1;
while (top <= bottom && left <= right) {
// Traverse top row left-to-right
for (int col = left; col <= right; ++col) {
result.push_back(matrix[top][col]);
}
++top;
// Traverse right column top-to-bottom
for (int row = top; row <= bottom; ++row) {
result.push_back(matrix[row][right]);
}
--right;
// Traverse bottom row right-to-left
// Handle the case where there is only a single row first, preventing
// double-counting
if (top <= bottom) {
for (int col = right; col >= left; --col) {
result.push_back(matrix[bottom][col]);
}
--bottom;
}
// Traverse left column bottom-to-top
// Handle the case where there is a single column left
if (left <= right) {
for (int row = bottom; row >= top; --row) {
result.push_back(matrix[row][left]);
}
++left;
}
}
return result;
}
};