How to rotate an array (array) in Java?

Asked

Viewed 1,278 times

2

I have a two-dimensional array, of size M x N, that stores Tiles of a map, in the following format:

[1, 2, 3],

[4, 5, 6],

[7, 8, 9],

[10, 11, 12]

And I want to rotate 90º (e.g., turn the map so that the North is in the East). The rotated example would look like this:

[10, 7, 4, 1],

[11, 8, 5, 2],

[12, 9, 6, 3]

Note that the matrix changed in size: it went to N x M after rotation. This is similar to what happens when rotating certain pieces of the Tetris game: the longer (high) it is, the wider it will be when rotated.

How to rotate this kind of two-dimensional array in Java?

1 answer

4


In the example, the 4x3 matrix can be declared as follows:

 int[][] a1 = new int[][]{   new int[]{1,2,3},
                             new int[]{4,5,6},
                             new int[]{7,8,9},
                             new int[]{10,11,12}};

That is, it is an array of int arrays. Below are described the codes to rotate two-dimensional arrays clockwise and counter-clockwise, respectively:

public static int[][] rotacionarMatrizHorario(int[][] matriz) {
    int largura = matriz.length;
    int altura = matriz[0].length;
    int[][] ret = new int[altura][largura];
    for (int i=0; i<altura; i++) {
        for (int j=0; j<largura; j++) {
            ret[i][j] = matriz[largura - j - 1][i];
        }
     }
    return ret;
}


public static int[][] rotacionarMatrizAntiHorario(int[][] matriz) {
    int largura = matriz.length;
    int altura = matriz[0].length;   
    int[][] ret = new int[altura][largura];
    for (int i=0; i<altura; i++) {
        for (int j=0; j<largura; j++) {
            ret[i][j] = matriz[j][altura - i - 1];
        }
    }
    return ret;
}

To turn a matrix "upside down", just rotate it twice in 90°, thus totaling 180°:

[12, 11, 10],
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]

By rotating the original matrix at 90º three times, that is, 270°, the result is the same as rotating the matrix at 90° counterclockwise. The result will be this:

[3, 6, 9, 12],
[2, 5, 8, 11],
[1, 4, 7, 10]

This is the simplest implementation: the methods have a complexity of the order of O(N²), where N is the size of the matrix, or more precisely O(M*N), where M is the height and N the width of the matrix.

Depending on the application, more efficient ways to rotate the matrix can be implemented. It is possible to decrease the complexity to O(N)*log(N), or even more, if special treatments are considered in the case of sparse matrices, or even optimizations according to the computer architecture that will make the rotations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.