Java 矩阵螺旋

1.题目: 矩阵螺旋

给定m × n个元素(m行,n列)的矩阵,以螺旋顺序返回矩阵的所有元素。输入为m n以及m*n的矩阵,输出螺旋顺序的所有元素

2.样例输入:

3 3

1 2 3

4 5 6

7 8 9

3.样例输出:

123698745

4.答案代码:

import java.util.Scanner;

class Main {

    public static void main(String[] args) {

        int flag = 1;
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        int n = sc.nextInt();
        int sum = m * n;
        int[][] arm = new int[m+1][n+1];

        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                arm[i][j] = sc.nextInt();
            }
        }
        int i = 1, j = 1, cnt = 1,cmm = 1;
        int ct = 0;
        while ((++ct) <= sum) {
            if (flag == 1) {
                System.out.print(arm[i][j++]);
                if (j == n){
                    flag = 2;
                    cmm++;
                }
                else{
                    continue;
                }
            }
            else if (flag == 2) {
                System.out.print(arm[i++][j]);
                if (i == m) {
                    flag = 3;
                    n--;
                }
                else{
                    continue;
                }
            }
            else if (flag == 3) {
                System.out.print(arm[i][j--]);
                if (j == cnt) {
                    flag = 4;
                    m--;
                }
                else{
                    continue;
                }
            }
            else if (flag == 4){
                System.out.print(arm[i--][j]);
                if (i == cmm) {
                    flag = 1;
                    cnt++;
                }
                else{
                    continue;
                }
            }
        }

    }

}
    

5.提交状态:

Java 矩阵螺旋

 

上一篇:随机生成四则运算题


下一篇:0911京东笔试