--- title: Matrix rotation 90 degrees description: Consider the algorithm for rotating a matrix 90 degrees clockwise and anticlockwise. This algorithm is similar to matrix transpose, with the difference... sections: [Transpose,Comparing algorithms] tags: [java,arrays,multidimensional arrays,matrices,rows,columns,loops,nested loops] canonical_url: /en/2021/12/13/matrix-rotation-90-degrees.html url_translated: /ru/2021/12/12/matrix-rotation-90-degrees.html title_translated: Поворот матрицы на 90 градусов date: 2021.12.13 lang: en --- 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. ```java // 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]({{ '/en/2021/12/17/matrix-rotation-180-degrees.html' | relative_url }}).* 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`}. ```java /** * @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; } ``` {% raw %} ```java // 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)); } ``` {% endraw %} ```java // 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 ```