给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 输出:[1,2,3,6,9,8,7,4,5]
提示:
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 10
- -100 <= matrix[i][j] <= 100
由题分析可得,可以将走过的路设置为 matrix[i][j] 取值范围外的值例如 -101,当走到转角 (数组边界 / matrix[i][j] == -101) 处按照顺时针进行对应转向,当无路可走 (数组越界 / matrix[i][j] == -101) 时终止循环。实现如下:
private int width;
private int height;
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>((height = matrix.length) * (width = matrix[0].length));
int value;
while ((value = getNext(matrix)) != -101) result.add(value);
return result;
}
public static final int LEFT = 1;
public static final int RIGHT = 2;
public static final int UP = 3;
public static final int DOWN = 4;
private int vector = RIGHT;
private int x = 0, y = 0;
private int getNext(int[][] map) {
if (x < 0 || y < 0 || x == width || y == height || map[y][x] == -101) return -101;
int value = map[y][x];
map[y][x] = -101; // 标记走过
switch (vector) {
case LEFT:
if (x-1 < 0 || map[y][x-1] == -101) {
vector = UP;
-- y;
} else {
-- x;
}
break;
case RIGHT:
if (x+1 >= width || map[y][x+1] == -101) {
vector = DOWN;
++ y;
} else {
++ x;
}
break;
case UP:
if (y-1 < 0 || map[y-1][x] == -101) {
vector = RIGHT;
++ x;
} else {
-- y;
}
break;
case DOWN:
if (y+1 >= height || map[y+1][x] == -101) {
vector = LEFT;
-- x;
} else {
++ y;
}
break;
}
return value;
}