File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < vector>
2
+
3
+ std::vector<int > spiralMatrix (std::vector<std::vector<int >>& matrix) {
4
+ if (matrix.empty ()) {
5
+ return {};
6
+ }
7
+ std::vector<int > result;
8
+ // Initialize the matrix boundaries.
9
+ int top = 0 , bottom = matrix.size () - 1 ;
10
+ int left = 0 , right = matrix[0 ].size () - 1 ;
11
+ // Traverse the matrix in spiral order.
12
+ while (top <= bottom && left <= right) {
13
+ // Move from left to right along the top boundary.
14
+ for (int i = left; i <= right; i++) {
15
+ result.push_back (matrix[top][i]);
16
+ }
17
+ top++;
18
+ // Move from top to bottom along the right boundary.
19
+ for (int i = top; i <= bottom; i++) {
20
+ result.push_back (matrix[i][right]);
21
+ }
22
+ right--;
23
+ // Check that the bottom boundary hasn't passed the top boundary
24
+ // before moving from right to left along the bottom boundary.
25
+ if (top <= bottom) {
26
+ for (int i = right; i >= left; i--) {
27
+ result.push_back (matrix[bottom][i]);
28
+ }
29
+ bottom--;
30
+ }
31
+ // Check that the left boundary hasn't passed the right boundary
32
+ // before moving from bottom to top along the left boundary.
33
+ if (left <= right) {
34
+ for (int i = bottom; i >= top; i--) {
35
+ result.push_back (matrix[i][left]);
36
+ }
37
+ left++;
38
+ }
39
+ }
40
+ return result;
41
+ }
You can’t perform that action at this time.
0 commit comments