Skip to content

Commit f3abcb5

Browse files
committed
feat(cpp): add spiral_matrix.cpp
1 parent 771b727 commit f3abcb5

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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+
}

0 commit comments

Comments
 (0)