[LeetCode] Spiral Matrix III

885. Spiral Matrix III

You start at the cell (rStart, cStart) of an rows x cols grid facing east. The northwest corner is at the first row and column in the grid, and the southeast corner is at the last row and column.

You will walk in a clockwise spiral shape to visit every position in this grid. Whenever you move outside the grid’s boundary, we continue our walk outside the grid (but may return to the grid boundary later.). Eventually, we reach all rows * cols spaces of the grid.

Return an array of coordinates representing the positions of the grid in the order you visited them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
int len = 1, rep = 2, cur = 1;
vector<vector<int>> res;
int y = rStart, x = cStart;
int dy[4]{-1,0,1,0},dx[4]{0,1,0,-1},d=1;
while(res.size() < rows*cols) {
if(0 <= y and y < rows and 0 <= x and x < cols) {
res.push_back({y,x});
}
y += dy[d], x += dx[d];
if(--cur == 0) {
d = (d + 1) % 4;
if(--rep == 0) {
rep = 2;
cur = len = len + 1;
} else cur = len;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/12/PS/LeetCode/spiral-matrix-iii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.