给定m × n个元素(m行,n列)的矩阵,以螺旋顺序返回矩阵的所有元素。输入为m n以及m*n的矩阵,输出螺旋顺序的所有元素
3 3
1 2 3
4 5 6
7 8 9
123698745
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; } } } } }