Consider the algorithm for rotating a matrix 90 degrees clockwise and anticlockwise. This algorithm is similar to matrix transpose, with the difference that here, for each point, one of the coordinates is mirrored.
// matrix transpose — rows and columns are swapped
swapped[j][i] = matrix[i][j];
// clockwise ↻ — rows are mirrored
rotated[j][i] = matrix[m-i-1][j];
// anticlockwise ↺ — columns are mirrored
rotated[j][i] = matrix[i][n-j-1];
Similar algorithm: Matrix rotation 180 degrees.
Let’s write a method in Java to rotate a matrix {m×n
} 90 degrees. The additional parameter
sets the direction of rotation: clockwise or anticlockwise. As an example, let’s take a
rectangular matrix {4×3
}.
/**
* @param m number of rows of the original matrix
* @param n number of columns of the original matrix
* @param clock direction of rotation:
* clockwise ↻ or anticlockwise ↺
* @param matrix the original matrix
* @return the rotated matrix
*/
public static int[][] rotateMatrix(int m, int n, boolean clock, int[][] matrix) {
// new matrix, the number of rows and columns are swapped
int[][] rotated = new int[n][m];
// bypass the rows of the original matrix
for (int i = 0; i < m; i++)
// bypass the columns of the original matrix
for (int j = 0; j < n; j++)
if (clock) // clockwise rotation ↻
rotated[j][i] = matrix[m-i-1][j];
else // anticlockwise rotation ↺
rotated[j][i] = matrix[i][n-j-1];
return rotated;
}
// start the program and output the result
public static void main(String[] args) {
// incoming data
int m = 4, n = 3;
int[][] matrix = {{11, 12, 13}, {14, 15, 16}, {17, 18, 19}, {20, 21, 22}};
// rotate the matrix and output the result
outputMatrix("Original matrix:", matrix);
outputMatrix("Clockwise ↻:", rotateMatrix(m, n, true, matrix));
outputMatrix("Anticlockwise ↺:", rotateMatrix(m, n, false, matrix));
}
// helper method, prints the matrix to the console row-wise
public static void outputMatrix(String title, int[][] matrix) {
System.out.println(title);
for (int[] row : matrix) {
for (int el : row)
System.out.print(" " + el);
System.out.println();
}
}
Output:
Original matrix:
11 12 13
14 15 16
17 18 19
20 21 22
Clockwise ↻:
20 17 14 11
21 18 15 12
22 19 16 13
Anticlockwise ↺:
13 16 19 22
12 15 18 21
11 14 17 20
© Golovin G.G., Code with comments, translation from Russian, 2021