问题描述
给出一个 m x n 的矩阵(m 行, n 列),请按照
顺时针螺旋顺序返回元素。
例如,给出以下矩阵:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
应该返回 [1,2,3,6,9,8,7,4,5]
解题思路和分析
方法一:模拟
直觉就是按照这个顺时针的顺序将数组中的数字输出。
矩阵有R行,C列,seen[r][c]数组用来标记是否被访问过。我们现在的位置是[r][c],前进的方向是di,我们要把数组内的所有元素都访问一遍。
当我们在数组内移动的时候,我们候选的下一个位置是(cr,cc)。如果(cr,cc)属于这个矩阵并且还没有被访问过,那么我们就移动到(cr,cc)。否则,我们应该顺时针转弯了。
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List ans = new ArrayList(); //存储结果
if (matrix.length == 0) return ans;
int R = matrix.length, C = matrix[0].length; //R行C列
boolean[][] seen = new boolean[R][C]; //boolean数组用来标记是否被访问过
int[]