classSolution{publicList<Integer>spiralOrder(int[][] matrix){List<Integer> res =newArrayList<>();// 定义四个指针int left =0;int right = matrix[0].length-1;int top =0;int bottom = matrix.length-1;while(true){for(int i = left ; i <= right;i++){
res.add(matrix[top][i]);}
top++;if(top>bottom)break;for(int i = top;i<= bottom;i++){
res.add(matrix[i][right]);}
right--;if(left>right)break;for(int i = right ; i>= left;i--){
res.add(matrix[bottom][i]);}
bottom--;if(bottom<top)break;for(int i = bottom ; i>=top;i--){
res.add(matrix[i][left]);}
left++;if(left>right)break;}return res;}}
3- ACM实现
publicclass spiralOrder {publicstaticList<Integer>spiral(int[][] matrix){List<Integer> res =newArrayList<>();// 四个指针int left =0;int right = matrix[0].length-1;int top =0;int buttom = matrix.length-1;// 2. 开始遍历while(true){// 第一行for(int i = left;i<=right;i++){
res.add(matrix[top][i]);}
top++;if(top>buttom)break;// 右侧第一列for(int i = top;i<=buttom;i++){
res.add(matrix[i][right]);}
right--;if(right<left)break;// 底下一行for(int i = right; i>= left;i--){
res.add(matrix[buttom][i]);}
buttom--;if(buttom<top)break;// 左侧一列for(int i = buttom;i>=top;i--){
res.add(matrix[i][left]);}
buttom--;if(buttom<top)break;}return res;}publicstaticvoidmain(String[] args){Scanner sc =newScanner(System.in);System.out.println("输入二维数组的行");int m = sc.nextInt();System.out.println("输入二维数组的列");int n = sc.nextInt();int[][] matrix =newint[m][n];System.out.println("输入二维数组的元素");for(int i =0; i < m;i++){for(int j =0; j < n ;j++){
matrix[i][j]= sc.nextInt();}}List<Integer> forRes =spiral(matrix);for(int i : forRes){System.out.print(i+" ");}}}