解决思路
模拟
绘制螺旋轨迹路径,我们发现当路径超出界限或者进入之前访问过的单元格时,会顺时针旋转方向。
public List<Integer> spiralOrder(int[][] matrix){
List ans = new ArrayList();
if(matrix.length == 0) return ans;
int R = matrix.length,C =matrix[0].length;
boolean[][] seen = new boolean[R][C];
int[][] d = new int[][]{{0,1},{1,0},{0,-1},{-1,0}};
int r = 0,c =0,di = 0;
for(int i =0;i<R*C;i++){
ans.add(matrix[r][c]);
seen[r][c] = true;
int cr = r + d[di][0];
int cc = c + d[di][1];
if(0<=cr && cr<R && 0<=cc && cc<C &&!seen[cr][cc]){
r = cr;
c = cc;
}else{
di = (di+1)%4;
r += d[di][0];
c += d[di][1];
}
}
return ans;
}