回行打印二维数组

回行打印二维数组

public class Test {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();

        int[][] arr = new int[n][m];
        Random random = new Random();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                arr[i][j] = random.nextInt(10);
            }
        }

        for (int i = 0; i < n; i++) {
            System.out.print("[");
            for (int j = 0; j < m; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.print("]");
            System.out.println();
        }
        System.out.println();

        int r_begin = 0, c_begin = 0;
        while (r_begin <= n || c_begin <= m) {
            for (int i = r_begin, j = c_begin; j < m && r_begin < n; j++)
                System.out.print(arr[i][j] + " ");
            r_begin++;
            for (int i = r_begin, j = m - 1; i < n && c_begin < m; i++)
                System.out.print(arr[i][j] + " ");
            m--;
            for (int i = n - 1, j = m - 1; j >= c_begin && r_begin < n; j--)
                System.out.print(arr[i][j] + " ");
            n--;
            for (int i = n - 1, j = c_begin; i >= r_begin && c_begin < m; i--)
                System.out.print(arr[i][j] + " ");
            c_begin++;
        }

    }
}

 

posted @ 2020-04-24 00:26  All_just_for_fun  阅读(503)  评论(0编辑  收藏  举报