public class 螺旋打印 { public List<Integer> spiralOrder(int[][] matrix) { int tR = 0; int tC = 0; int dR = matrix.length - 1; int dC = matrix[0].length - 1; List<Integer> list = new ArrayList<>(); while (tR <= dR && tC <= dC) { printList(matrix, list, tR++, tC++, dR--, dC--); } return list; } private void printList(int[][] matrix, List<Integer> list, int tR, int tC, int dR, int dC) { if (tR == dR) {//只有一行了 for (int i = tC; i <= dC; i++) { list.add(matrix[tR][i]); } } else if (tC == dC) {//只有一列了 for (int i = tR; i <= dR; i++) { list.add(matrix[i][tC]); } } else {//一般情况 int curR = tR; int curC = tC; while (curC < dC) { list.add(matrix[tR][curC++]); } while (curR < dR) { list.add(matrix[curR++][dC]); } while (curC > tC) { list.add(matrix[dR][curC--]); } while (curR > tR) { list.add(matrix[curR--][tC]); } } } public static void main(String[] args) { int[][] nums = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12} }; System.out.println(new 螺旋打印().spiralOrder(nums)); } }