题解如代码:
public ArrayList<Integer> printMatrix(int [][] matrix) { int[] dx = {0,1,0,-1}; int[] dy = {1,0,-1,0}; int i =0,j=0; int rows = matrix.length; int cols = matrix[0].length; boolean[][] visited = new boolean[rows][cols]; int max = matrix.length * matrix[0].length; ArrayList<Integer> list = new ArrayList<>(); for(int k = 0,d =0;k < max;k++){ //转向 list.add(matrix[i][j]); visited[i][j] = true; int nextI = i + dx[d]; int nextJ = j + dy[d]; if(nextI<0 || nextI>=rows || nextJ<0 || nextJ>=cols || visited[nextI][nextJ]){ d = (d+1)%4; } i = i + dx[d]; j = j + dy[d]; } return list; }