Search code examples
javaarraysmultidimensional-arrayrotationtranspose

Rotating multi-dimensional array by 90 degrees clockwise


I've been able to work out the bulk of the problem. But my output keeps throwing an exception. I'm sure it's something minor, but I can't seem to figure out how to make this work right. I'm including the exception, the task as originally worded to me, along with my code so far:

Using formula array[j][n - 1 - i] I get the following exception:

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

If I use array[j][n - i] I get no exception, but it isn't the correct output order.

Been stuck on this for a week!

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("");
        }
    }
}

Solution

  • If you're only rotating it 90 degrees, you're just starting from the end of the row to the beginning while moving columns left and right. So your code should just be:

    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("");
    }