class Solution { public int[] spiralOrder(int[][] matrix) { //判空 if(matrix.length == 0){ return new int[0]; } //定义矩阵 上下左右的边界 int left = 0; int right = matrix[0].length - 1; int top = 0; int bottom = matrix.length - 1; //定义 存放的数组 res,及数组的下标index int[] res = new int[(right + 1) * (bottom + 1)]; int index = 0; while(true){ //从左往右 for(int i = left;i <= right;i++){ res[index++] = matrix[top][i]; } if(++top > bottom){ break; } //从上往下 for(int i = top;i <= bottom;i++){ res[index++] = matrix[i][right]; } if(left > --right){ break; } //从右往左 for(int i = right; i >= left;i--){ res[index++] = matrix[bottom][i]; } if(top > --bottom){ break; } //从下往上 for(int i = bottom;i >= top; i--){ res[index++] = matrix[i][left]; } if(++left > right){ break; } } return res; } }