每次都是转圈打印,所以记二维数组的左上和右下坐标,一圈圈打印即可
public static ArrayList<Integer> printMatrix(int [][] matrix) { if(matrix==null||matrix.length==0)return null; ArrayList<Integer> res = new ArrayList<>(); return printCircle(res,matrix,0,0,matrix.length-1,matrix[0].length-1); } private static ArrayList<Integer> printCircle(ArrayList<Integer> res,int[][] arr,int row1,int col1,int row2,int col2){ int curR= row1; int curC = col1; //递归结束条件 if(col1-col2>0||row1-row2>0) return res; //如果只有一行 if(row1==row2){ for (int i = col1; i <=col2 ; i++) { res.add(arr[row2][i]); } return res; }else if (col1==col2){ for (int i = row1; i <=row2 ; i++) { res.add(arr[i][col1]); } return res; } while (curC<col2) { res.add(arr[curR][curC++]); } while(curR<row2){ res.add(arr[curR++][curC]); } while (curC>col1){ res.add(arr[curR][curC--]); } while (curR>row1){ res.add(arr[curR--][curC]); } return printCircle(res,arr,++row1,++col1,--row2,--col2); }