下面的代码可以复用,只需要按照打印的要求调整directions数组就可以正确进行打印。
public ListspiralOrder(int[][] matrix) { List order = new ArrayList (); if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return order; } int rows = matrix.length, columns = matrix[0].length; boolean[][] visited = new boolean[rows][columns]; int total = rows * columns; int row = 0, column = 0; int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; int directionIndex = 0; for (int i = 0; i < total; i++) { order.add(matrix[row][column]); visited[row][column] = true; // 使用nextRow和nextColumn提前进行检验,如果不符合要求,就修改index,让row和column正确变化。 int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1]; if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn]) { directionIndex = (directionIndex + 1) % 4; } row += directions[directionIndex][0]; column += directions[directionIndex][1]; } return order; }



