1.思路:模拟顺时针打印的过程,从{0, 0}开始。遍历矩阵,最开始是向右,当row或者col超过下标或者元素已经被访问,则改变访问的方向。
2.代码:
class Solution {
public int[] spiralOrder(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0)return new int[0];
int rows = matrix.length, cols = matrix[0].length;
int[] res = new int[rows * cols];
boolean[][] vis = new boolean[rows][cols];
int row = 0, col = 0;
int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int directionIndex = 0;
for(int i = 0 ; i < rows * cols; i++){
res[i] = matrix[row][col];
vis[row][col] = true;
int nexRow = row + directions[directionIndex][0];
int nexCol = col + directions[directionIndex][1];
if(nexRow < 0 || nexRow >= rows || nexCol < 0 || nexCol >= cols || vis[nexRow][nexCol]){
directionIndex = (directionIndex + 1) % 4;
}
row += directions[directionIndex][0];
col += directions[directionIndex][1];
}
return res;
}
}
3.复杂度分析:时间0(mn),m,n分别是矩阵的行和列,空间o(mn),需要欸外的vis数组。