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.