视频讲解中的思路图解
代码
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList();
if(matrix == null || matrix.length < 1) return result;
int m = matrix.length, n = matrix[0].length;
int[] dx = {0,1,0,-1}, dy = {1,0,-1,0};
boolean[][] used = new boolean[m][n];
for(int i = 0, x = 0, y = 0, d = 0; i < m * n; i++){
result.add(matrix[x][y]);
used[x][y] = true;
//检验下一个位置是否合法, 不合法则更新方向, 并重新计算下一个位置
int a = x + dx[d], b = y + dy[d];
if( a < 0 || a >= m || b < 0 || b >= n || used[a][b]){
d ++;
d %= 4;
a = x + dx[d];
b = y + dy[d];
}
x = a ;
y = b;
}
return result;
}
}