Untitled
unknown
c_cpp
a year ago
1.2 kB
11
Indexable
class Solution {
public:
int vec[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
vector<vector<int>> res;
int aria_count = 0, target_aria = rows * cols;
int y = rStart, x = cStart;
int step_count = 0, target_step = 1;
int direction = 0;
bool twice = false;
while (aria_count < target_aria) {
// Check if position is in the grid
if (y >= 0 && y < rows && x >= 0 && x < cols) {
aria_count += 1;
res.push_back({y, x});
}
if (step_count == target_step) {
step_count = 0;
direction = (direction + 1) % 4;
if (twice) { // Walk in same direction 2 times
twice = false;
target_step += 1;
} else {
twice = true;
}
}
y = y + vec[direction][0];
x = x + vec[direction][1];
step_count += 1;
}
return res;
}
};Editor is loading...
Leave a Comment