题目链接
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.
题解:
Medium的题无需多言,直接上代码:
class Solution {
public:
vector<vector<int>> spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
int drc[4][2] = {{0,1},{1,0},{0,-1},{-1,0}},dn = 0, dp[2] = {1,1}, end = rows*cols, ln=0;
vector<vector<int>> rst(end, {0,0});
rst[ln][0] = rStart;
rst[ln++][1] = cStart;
while(ln < end) {
for(int i = 0; i< dp[dn&1]; i++) {
rStart += drc[dn][0];
cStart += drc[dn][1];
if (isInMatrix(rStart, rows) && isInMatrix(cStart, cols)) {
rst[ln][0] = rStart;
rst[ln++][1] = cStart;
}
}
++dp[dn&1];
(++dn) %= 4;
}
return rst;
}
inline bool isInMatrix(int x, int ln) {
return x>= 0 && x <ln;
}
};