Skip to content

Commit 32dfcf4

Browse files
authored
Create spiral-matrix-iii.cpp
1 parent 5e7e00b commit 32dfcf4

1 file changed

Lines changed: 21 additions & 0 deletions

File tree

C++/spiral-matrix-iii.cpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Time: O(max(m, n)^2)
2+
// Space: O(1)
3+
4+
class Solution {
5+
public:
6+
vector<vector<int>> spiralMatrixIII(int R, int C, int r0, int c0) {
7+
int r = r0, c = c0;
8+
vector<vector<int>> result = {{r, c}};
9+
int x = 0, y = 1, i = 0, n = 0;
10+
while (result.size() < R * C) {
11+
r += x, c += y, ++i;
12+
if (0 <= r && r < R && 0 <= c && c < C) {
13+
result.push_back({r, c});
14+
}
15+
if (i == n / 2 + 1) {
16+
swap(x, y), y *= -1, ++n, i = 0;
17+
}
18+
}
19+
return result;
20+
}
21+
};

0 commit comments

Comments
 (0)