剑指 Offer 29. 顺时针打印矩阵
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
思路分析:依据题意,是顺时针打印矩阵,所以打印方向就是右、下、左、上。一直重复这个过程直到打印结束。所以我们可以定义一个direction方向数组,以及visit访问数组,如果已经访问过了,或者访问的索引越界了,我们就更新方向。
class Solution {
public int[] spiralOrder(int[][] matrix) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return new int[0];
}
// rows columns and total
int rows = matrix.length;
int columns = matrix[0].length;
int total = rows * columns;
int[] result = new int[total];
// directions right down left up
int[][] direction = {{0,1},{1,0},{0,-1},{-1,0}};
// visit
boolean[][] visist = new boolean[rows][columns];
int direction_index = 0;
int row = 0,column = 0;
for(int i = 0;i < total;i++){
// print
result[i] = matrix[row][column];
//update the visit
visist[row][column] = true;
// check the index
int next_row = row + direction[direction_index][0];
int next_column = column + direction[direction_index][1];
if(next_column < 0 || next_column >= columns || next_row < 0 || next_row >= rows || visist[next_row][next_column]){
// change the direction
direction_index = (direction_index + 1) % 4;
}
// update the row and column
row += direction[direction_index][0];
column += direction[direction_index][1];
}
return result;
}
}
很明显,如果矩阵的大小是mn,那么时间复杂度是O(mn),而由于题目要求返回数组,所以空间复杂度是O(1);