剑指 Offer 29. 顺时针打印矩阵
count
来维护当前打印的第几层count*2<column && count*2<row
class Solution { public int[] spiralOrder(int[][] matrix) { if (matrix.length == 0) { return new int[0]; } int column = matrix[0].length; int row = matrix.length; // int[] res = new int[column * row]; // 写入到res数组的指针 int position = 0; // 代表的是第几遍循环 int count = 0; while (count*2 < column && count*2 < row) { int endColumn = column - 1 - count; int endRow = row - 1 - count; // 打印上方 // 只有这个不用判断,因为是最先打印的这个 // 如果最内圈只有一行,那么其他三个方向就都不要打印了,所以其他三个方向要判断 for (int i = count; i <= endColumn; i++) { res[position++] = matrix[count][i]; } // 打印右侧 if (count < endRow) { for (int i = count+1; i <= endRow; i++) { res[position++] = matrix[i][endColumn]; } } // 打印下方 if (count < endColumn && count < endRow) { for (int i = endColumn-1; i >= count; i--) { res[position++] = matrix[endRow][i]; } } // 打印左侧 if (count < endColumn && count < endRow) { for (int i = endRow-1; i > count; i--) { res[position++] = matrix[i][count]; } } count++; } return res; } }