
public static void main(String[] args) {int [][] nums=new int[][]{{ 1,2,3}, { 4,5,6}, {7,8,9}};ArrayList<Integer> results = (ArrayList<Integer>) spiralOrder(nums);System.out.println("输入为:"+Arrays.deepToString(nums));System.out.print("输出为:"); System.out.println(results);}public static List<Integer> spiralOrder(int[][] numlist) {List<Integer> list = new ArrayList<>();if (numlist == null || numlist.length == 0 || numlist[0].length == 0)return list;int rowMin = 0, rowMax = numlist.length - 1, colMin = 0, colMax = numlist[0].length - 1;//顺时针:从左到右,从上到下,从右到左,从下到上while (rowMin <= rowMax && colMin <= colMax) {/*遍历第一行,行不动,列加1* 遍历结果1->2->3*/for (int i = colMin; i <= colMax; i++)list.add(numlist[rowMin][i]);rowMin++;/*遍历最后一列colMax,列不动,行加1* 遍历结果3->6->9*/for (int i = rowMin; i <= rowMax; i++)list.add(numlist[i][colMax]);colMax--;if (rowMin > rowMax || colMin > colMax)break;/*遍历最后一行rowMax,行不动,列减1* 遍历结果9->8->7*/for (int i = colMax; i >= colMin; i--)list.add(numlist[rowMax][i]);rowMax--;/*遍历第一列colMin,列不动,行减1* ......*/for (int i = rowMax; i >= rowMin; i--)list.add(numlist[i][colMin]);colMin++;}return list;}
