注意避坑:
代码里面:当读到M=-1,N=-1时,输入终止;
如果使用sc.close就无法通过;但是换用break就可以ac!!!
自己也不清楚为什么,这块折腾了好长时间,因此,在此特意提醒。

import java.util.Scanner;

/**
 * @program: Leetcode
 * @Author: X.Q.X
 * @Date: 2021-08-04 09:52
 */
public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String[] tmp = sc.nextLine().split(" ");
            int m = Integer.parseInt(tmp[0]);
            int n = Integer.parseInt(tmp[1]);

            //注意避坑:这里如果使用sc.close就无法通过;但是换用break就可以ac!!!
            if (m == -1 && n == -1) break;

            int[][] matrix = new int[m][n];
            for(int i = 0; i < m; i++) {
                String[] temp = sc.nextLine().trim().split(" ");
                for(int j = 0; j < n; j++)
                    matrix[i][j] = Integer.parseInt(temp[j]);
            }

//            System.out.println(Arrays.toString(matrix[0]));
//            System.out.println(Arrays.toString(matrix[1]));
//            System.out.println(Arrays.toString(matrix[2]));

            System.out.println(spiralOrder(matrix));
        }
    }

    //方法一:递归 + 模拟(按层模拟递归)
    private static String spiralOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return "";

        int m = matrix.length, n = matrix[0].length;
        int[] res = new int[m * n];

        int index = 0;
        int left = 0, right = n - 1, top = 0, bottom = m - 1;
        while (left <= right && top <= bottom) {
            for (int col = left; col <= right; col++) {
                res[index++] = matrix[top][col];
            }

            for (int row = top + 1; row <= bottom; row++) {
                res[index++] = matrix[row][right];
            }

            if (left < right && top < bottom) {
                for (int col = right - 1; col > left; col--) {
                    res[index++] = matrix[bottom][col];
                }

                for (int row = bottom; row > top; row--) {
                    res[index++] = matrix[row][left];
                }
            }
            left++;
            top++;
            right--;
            bottom--;
        }

        StringBuilder ret = new StringBuilder();
        for (int i = 0; i < res.length - 1; i++) {
            ret.append(res[i]).append(",");
        }
        ret.append(res[res.length - 1]);
        return ret.toString();
    }
}