3/jekyll_site/en/2021/12/17/matrix-rotation-180-degrees.md
2023-12-17 07:56:19 +03:00

2.5 KiB
Raw Blame History

title description sections tags canonical_url url_translated title_translated date lang
Matrix rotation 180 degrees 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...
Transpose
Comparing algorithms
java
arrays
multidimensional arrays
matrices
rows
columns
loops
nested loops
/en/2021/12/17/matrix-rotation-180-degrees.html /ru/2021/12/16/matrix-rotation-180-degrees.html Поворот матрицы на 180 градусов 2021.12.17 en

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]({{ '/en/2021/12/13/matrix-rotation-90-degrees.html' | relative_url }}).

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;
}

{% raw %}

// 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));
}

{% endraw %}

// 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