Skip to content

Commit 0551458

Browse files
author
kwu130
committed
feat(src): add 54-spiralOrder
1 parent 7d4f070 commit 0551458

1 file changed

Lines changed: 75 additions & 0 deletions

File tree

‎src/54-spiralOrder.cpp‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
//
2+
// Created by 1412 on 2025/10/31.
3+
//
4+
5+
#include <bits/stdc++.h>
6+
7+
using namespace std;
8+
9+
class Solution {
10+
public:
11+
vector<int> spiralOrder(vector<vector<int>>& matrix) {
12+
int m = matrix.size();
13+
int n = matrix[0].size();
14+
vector<int> res;
15+
res.reserve(m * n);
16+
int i = 0, j = 0;
17+
while (res.size() < m * n) {
18+
while (i >= 0 && i < m && j >= 0 && j < n && matrix[i][j] != INT_MIN) {
19+
res.push_back(matrix[i][j]);
20+
matrix[i][j] = INT_MIN;
21+
j++;
22+
}
23+
j--;
24+
i++;
25+
while (i >= 0 && i < m && j >= 0 && j < n && matrix[i][j] != INT_MIN) {
26+
res.push_back(matrix[i][j]);
27+
matrix[i][j] = INT_MIN;
28+
i++;
29+
}
30+
i--;
31+
j--;
32+
while (i >= 0 && i < m && j >= 0 && j < n && matrix[i][j] != INT_MIN) {
33+
res.push_back(matrix[i][j]);
34+
matrix[i][j] = INT_MIN;
35+
j--;
36+
}
37+
j++;
38+
i--;
39+
while (i >= 0 && i < m && j >= 0 && j < n && matrix[i][j] != INT_MIN) {
40+
res.push_back(matrix[i][j]);
41+
matrix[i][j] = INT_MIN;
42+
i--;
43+
}
44+
i++;
45+
j++;
46+
}
47+
return res;
48+
}
49+
};
50+
51+
void test() {
52+
Solution s;
53+
vector<vector<int>> matrix = {
54+
{1, 2, 3},
55+
{4, 5, 6},
56+
{7, 8, 9}
57+
};
58+
vector<int> expected = {1, 2, 3, 6, 9, 8, 7, 4, 5};
59+
vector<int> res = s.spiralOrder(matrix);
60+
assert(res == expected);
61+
62+
matrix = {
63+
{1, 2, 3, 4},
64+
{5, 6, 7, 8},
65+
{9, 10, 11, 12}
66+
};
67+
expected = {1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7};
68+
res = s.spiralOrder(matrix);
69+
assert(res == expected);
70+
}
71+
72+
int main() {
73+
test();
74+
return 0;
75+
}

0 commit comments

Comments
 (0)