package leetcode; import java.util.ArrayList; import java.util.List; public class demo_54 { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> list=new ArrayList<Integer>(); //最外圈的宽度 int width=matrix[0].length; //最外圈的高度 int height=matrix.length; int length=width*height; //记录每一次开始的位置 int start=0; int i; int j; //每一次走完一个完整的外圈 while(list.size()<length) { i=start; j=start; for(;j<width&&list.size()<length;j++) { list.add(matrix[i][j]); } j=j-1; for(i=i+1;i<height&&list.size()<length;i++) { list.add(matrix[i][j]); } i=i-1; for(j=j-1;j>=start&&list.size()<length;j--) { list.add(matrix[i][j]); } j=j+1; for(i=i-1;i>start&&list.size()<length;i--) { list.add(matrix[i][j]); } start=start+1; width=width-1; height=height-1; } for(int num:list) { System.out.print(num+" "); } return list; } public static void main(String[] args) { // TODO Auto-generated method stub demo_54 d54=new demo_54(); int nums[][]= {{1,2,3,4},{5,6,7,8},{9,10,11,12}}; d54.spiralOrder(nums); } }