顺时针旋转多维数组90度

Rotating multi-dimensional array by 90 degrees clockwise

我已经解决了大部分问题。但是我的输出不断抛出异常。我敢肯定这是小事,但我似乎无法弄清楚如何使这项工作正常进行。我包括例外情况,最初给我的任务,以及我目前的代码:

使用公式 array[j][n - 1 - i] 我得到以下异常:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 4 at com.company.Main.main(Main.java:20)

如果我使用 array[j][n - i] 我也没有例外,但它不是正确的输出顺序。

一个星期都卡在这上面了!

Given a rectangle array n×m in size. Rotate it by 90 degrees clockwise, by recording the result into the new array m×n in size.

Input data format:

Input the two numbers n and m, not exceeding 100, and then an array n×m in size.

Output data format:

Output the resulting array. Separate numbers by a single space in the output.

Sample Input 1:

3 4

11 12 13 14
21 22 23 24
31 32 33 34

Sample Output 1:

31 21 11
32 22 12
33 23 13
34 24 14
class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int m = scanner.nextInt();
        int[][] array = new int[n][m];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                array[i][j] = scanner.nextInt();
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(array[j][n - 1 - i] + " ");
            }
            System.out.println("");
        }
    }
}

如果您只是将其旋转 90 度,那么您只是从行尾开始,同时左右移动列。所以你的代码应该是:

int n = 3;
int m = 4;

int[][] array = {
        {11, 12, 13, 14},
        {21, 22, 23, 24},
        {31, 32, 33, 34}};

for (int col = 0; col < m; col++) {
    for (int row = n - 1; row >= 0; row--) {
        System.out.print(array[row][col] + " ");
    }
    System.out.println("");
}