MAIN

EN

Matrix rotation 180 degrees

Transpose • Comparing algorithms
17.12.2021

Consider the algorithm for rotating a matrix 180 degrees. Unlike the transpose algorithm, here in the resulting matrix the rows and columns are not swapped, but are mirrored.

// rows and columns are swapped
swapped[j][i] = matrix[i][j];
// rows and columns are mirrored
rotated[i][j] = matrix[m-i-1][n-j-1];

Similar algorithm: Matrix rotation 90 degrees.

Let’s write a method in Java to rotate a matrix {m×n} 180 degrees. 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 matrix the original matrix
 * @return the rotated matrix
 */
public static int[][] rotateMatrix(int m, int n, int[][] matrix) {
    // new matrix
    int[][] rotated = new int[m][n];
    // 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++)
            // rows and columns are mirrored
            rotated[i][j] = matrix[m-i-1][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("Rotation by 180°:", rotateMatrix(m, n, 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
Rotation by 180°:
 22 21 20
 19 18 17
 16 15 14
 13 12 11

© Golovin G.G., Code with comments, translation from Russian, 2021

Upward