Re: [闲聊] 每日leetcode

楼主: smart0eddie (smart0eddie)   2024-08-08 11:34:33
2024-08-08
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.
好像只能照着刻然后一格一格走塞进去欸?
在外面的时候可能可以用数学解跳过吧
可是感觉好麻烦
基本上萝悬是从最小圈开始往前走一格以后转弯
每转弯两次会碰到上一圈的 要多走一格
class Solution {
public:
vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart, int
cStart) {
const vector<vector<int>> ds = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
const int grids_number = rows * cols;
vector<vector<int>> results;
int max_step = 1;
int dir = 0;
int step = 0;
int x = cStart, y = rStart;
while (results.size() < grids_number) {
if (isInside(x, y, rows, cols)) {
results.push_back({y, x});
}
x += ds[dir][0];
y += ds[dir][1];
step++;
if (step == max_step) {
step = 0;
dir = (dir + 1) % 4;
if (!(dir % 2)) {
max_step++;
}
}
}
return results;
}
private:
inline bool isInside(const int x, const int y, const int rows, const int
cols) {
return x >=0 && x < cols && y >= 0 && y < rows;
}
};
作者: oin1104 (是oin的说)   2024-08-08 11:35:00
大师
作者: dont   2024-08-08 13:38:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com