试题 基础练习 回形取数


问题描述
  回形取数就是沿矩阵的边取数,若当前方向上无数可取或已经取过,则左转90度。一开始位于矩阵左上角,方向向下。
输入格式
  输入第一行是两个不超过200的正整数m, n,表示矩阵的行和列。接下来m行每行n个整数,表示这个矩阵。
输出格式
  输出只有一行,共mn个数,为输入矩阵回形取数得到的结果。数之间用一个空格分隔,行末不要有多余的空格。
样例输入
3 3
1 2 3
4 5 6
7 8 9
样例输出
1 4 7 8 9 6 3 2 5
样例输入
3 2
1 2
3 4
5 6
样例输出
1 3 5 6 4 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        int m = input.nextInt();
        List<Integer> result = new ArrayList<>();
        int[][] a = new int[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                a[i][j] = input.nextInt();
            }
        }
        input.close();
        while (a.length > 2 && a[0].length > 2) {
            helper2(a, result);
            a = helper1(a);
        }
        helper2(a, result);
        for (Integer integer : result) {
            System.out.print(integer + " ");
        }
    }

    public static int[][] helper1(int[][] a) {
        int[][] b = new int[a.length - 2][a[0].length - 2];
        for (int i = 1; i < a.length - 1; i++)
            if (a[0].length - 1 - 1 >= 0)
                System.arraycopy(a[i], 1, b[i - 1], 0, a[0].length - 1 - 1);
        return b;
    }

    public static void helper2(int[][] a, List<Integer> m) {
        if (a.length == 1 && a[0].length != 1) {
            for (int i = 0; i < a[0].length; i++)
                m.add(a[0][i]);
        }
        if (a[0].length == 1 && a.length != 1) {
            for (int[] ints : a) {
                m.add(ints[0]);
            }
        }
        if (a.length == 1 && a[0].length == 1) {
            m.add(a[0][0]);
        }
        if (a.length > 1 && a[0].length > 1) {
            for (int[] ints : a) {
                m.add(ints[0]);
            }
            for (int i = 1; i < a[0].length; i++) {
                m.add(a[a.length - 1][i]);
            }
            for (int i = a.length - 1 - 1; i >= 0; i--) {
                m.add(a[i][a[0].length - 1]);
            }
            for (int i = a[0].length - 1 - 1; i > 0; i--) {
                m.add(a[0][i]);
            }
        }
    }
}
/*这其实就像给矩阵脱衣服一样,
  helper1帮矩阵外围脱掉,helper2记录“被拖掉衣服”的顺序
  循环往复即可求解,这样理解就容易的多;但要注意一行或一列时的特殊情况
 */