[LeetCode] 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.
Example 1:
Input: rows = 1, cols = 4, rStart = 0, cStart = 0
Output: [[0,0],[0,1],[0,2],[0,3]]
Example 2:
Input: rows = 5, cols = 6, rStart = 1, cStart = 4
Output: [[1,4],[1,5],[2,5],[2,4],[2,3],[1,3],[0,3],[0,4],[0,5],[3,5],[3,4],[3,3],[3,2],[2,2],[1,2],[0,2],[4,5],[4,4],[4,3],[4,2],[4,1],[3,1],[2,1],[1,1],[0,1],[4,0],[3,0],[2,0],[1,0],[0,0]]
Constraints:
1 <= rows, cols <= 100
0 <= rStart < rows
0 <= cStart < cols
螺旋矩阵 III。
在 rows x cols 的网格上,你从单元格 (rStart, cStart) 面朝东面开始。网格的西北角位于第一行第一列,网格的东南角位于最后一行最后一列。你需要以顺时针按螺旋状行走,访问此网格中的每个位置。每当移动到网格的边界之外时,需要继续在网格之外行走(但稍后可能会返回到网格边界)。
最终,我们到过网格的所有 rows x cols 个空间。
按照访问顺序返回表示网格位置的坐标列表。
思路
这道题题意不难理解,但是有一个不太直观的地方是,我们在螺旋行走的时候,每一个方向到底走几步就可以换方向了。
复杂度
时间O(rc)
空间O(rc)
代码
Java实现
class Solution {
public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
int[][] res = new int[rows * cols][2];
int index = 0;
res[index++] = new int[] { rStart, cStart };
// directions, right, down, left, up
int[][] dirs = new int[][] { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
// 步长
int step = 1;
int r = rStart;
int c = cStart;
while (index < rows * cols) {
for (int i = 0; i < 4; i++) {
int[] dir = dirs[i];
for (int j = 0; j < step; j++) {
r += dir[0];
c += dir[1];
// 如果这个坐标在结果集的范围内,则把这个坐标加入结果集
if (r >= 0 && r < rows && c >= 0 && c < cols) {
res[index++] = new int[] { r, c };
}
}
// 往左走和往右走的时候,步长要+1
if (i == 1 || i == 3) {
step++;
}
}
}
return res;
}
}