Description:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
题意:给定一个二维数组,返回按螺旋访问的数组元素序列;具体的访问方式如下图所示:
解法:既然是按照螺旋的方式访问,那么我们就可以定义
- 四个方向(右移,下移,左移,上移)及一个变量记录前进方向
- 对访问过的元素进行标记的标记数组
- 当前的行和列
我们从当前行和列的位置出发,添加元素后,对当前的行和列进行四个方向的某一个方向的移动,此时,需要判断下一个元素的合法性(是否超出数组范围或者已访问过)来改变前进的方向;
Java
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if (matrix.length == 0) return result;
boolean[][] visited = new boolean[matrix.length][matrix[0].length];
int cnt = matrix.length * matrix[0].length;
int[][] step = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int stepIndex = 0;
int row = 0;
int col = 0;
while (cnt-- > 0) {
result.add(matrix[row][col]);
visited[row][col] = true;
int tempRow = row + step[stepIndex][0];
int tempCol = col + step[stepIndex][1];
if (tempRow >= 0 && tempRow < matrix.length &&
tempCol >= 0 && tempCol < matrix[0].length &&
!visited[tempRow][tempCol]) {
row = tempRow;
col = tempCol;
} else {
stepIndex = (stepIndex + 1) % step.length;
row += step[stepIndex][0];
col += step[stepIndex][1];
}
}
return result;
}
}