- import java.util.Scanner;
- public class 回形取数 {
- private static Scanner sc;
- public static void main(String[] args) {
- sc = new Scanner(System.in);
- String[] str1 = sc.nextLine().split(" ");
- int x = Integer.parseInt(str1[0]);
- int y = Integer.parseInt(str1[1]);
-
- String[][] arr = new String[x][y];
- for (int i = 0; i < x; i++) {
- String[] str = sc.nextLine().trim().split(" ");
- arr[i] =str;
-
- }
- spiralOrderPrint(arr);
- }
- public static void spiralOrderPrint(String[][] matrix) {
- int tR = 0;
- int tC = 0;
- int dR = matrix.length - 1;
- int dC = matrix[0].length - 1;
- while (tR <= dR && tC <= dC) {
- printEdge(matrix, tR++, tC++, dR--, dC--);
- }
- }
- public static void printEdge(String[][] m, int tR, int tC, int dR, int dC) {
- if (tR == dR) {
- for (int i = tC; i <= dC; i++) {
- System.out.print(m[tR][i] + " ");
- }
- } else if (tC == dC) {
- for (int i = tR; i <= dR; i++) {
- System.out.print(m[i][tC] + " ");
- }
- } else {
- int curC = tC;
- int curR = tR;
- while (curR != dR) {
- System.out.print(m[curR][tC] + " ");
- curR++;
- }
- while (curC != dC) {
- System.out.print(m[dR][curC] + " ");
- curC++;
- }
- while (curR != tR) {
- System.out.print(m[curR][dC] + " ");
- curR--;
- }
- while (curC != tC) {
- System.out.print(m[tR][curC] + " ");
- curC--;
- }
- }
- }
- }
复制代码 |