885_螺旋矩阵III

难度:中等

题目

在 R 行 C 列的矩阵上,我们从 (r0, c0) 面朝东面开始

这里,网格的西北角位于第一行第一列,网格的东南角位于最后一行最后一列。

现在,我们以顺时针按螺旋状行走,访问此网格中的每个位置。

每当我们移动到网格的边界之外时,我们会继续在网格之外行走(但稍后可能会返回到网格边界)。

最终,我们到过网格的所有 R * C 个空间。

按照访问顺序返回表示网格位置的坐标列表。

示例

示例一:

输入:R = 1, C = 4, r0 = 0, c0 = 0
输出:[[0,0],[0,1],[0,2],[0,3]]

示例二:

输入:R = 5, C = 6, r0 = 1, c0 = 4
输出:[[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]]

提示

  • 1 <= R <= 100
  • 1 <= C <= 100
  • 0 <= r0 < R
  • 0 <= c0 < C

解题

思路与螺旋矩阵II基本一致,只不过此题螺旋是由内向外,所以定义了最大边界,Left,Right,Upper,Bottom。

  • 向右到达右边界时,转向下,右边界扩大
  • 向下到达下边界时,转向左,下边界扩大
  • 向左到达左边界时,转向上,左边界扩大
  • 向上到达上边界时,转向右,上边界扩大

初始边界为初始位置上下左右加一

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) {
int[][] ans = new int[rows*cols][2];
int[][] directions = {{0,1},{1,0},{0,-1},{-1,0}};
int row = rStart, col = cStart,num=1,dirIndex = 0;
int Left = cStart-1, Right = cStart+1, Upper = rStart-1, Bottom = rStart+1;
while (num<=rows*cols){
if (row>=0 && row<rows && col>=0 && col<cols){
ans[num-1] = new int[]{row,col};
num++;
}
if (dirIndex==0 && col==Right){ // 到右边界
dirIndex +=1; // 方向向右转为向下
Right+=1; // 右边界右移
}
if (dirIndex==1&& row==Bottom){ // 到下边界
dirIndex +=1; // 方向由下转为向左
Bottom+=1; // 下边界下移
}
if (dirIndex==2 && col==Left){ // 到左边界
dirIndex +=1; // 方向由向左转为向上
Left-=1; // 左边界左移
}
if (dirIndex==3 && row==Upper) { // 到上边界
dirIndex = 0; // 方向由向上转为向右
Upper -=1; // 上边界上移
}
row += directions[dirIndex][0];
col += directions[dirIndex][1];
}
return ans;
}