Rotate Image

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Follow up: Could you do this in-place?

先按主对角线反转,再按垂直中轴线反转。

public class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix[0].length;
        int temp;

        //先按主对角线反转,相当于矩阵转置(matrix transpose)
        for(int i = 0; i < n; i++){
            for(int j = i+1; j < n; j++){
                temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }

         //再按垂直中轴线反转
        for(int i = 0; i < n; i++){
            for(int j = 0; j < n/2; j++){
                temp = matrix[i][j];
                matrix[i][j] = matrix[i][n-1-j];
                matrix[i][n-1-j] = temp;
            }
        }
    }
}

解法2 Matrix Rotation and Matrix Transpose

 /*
 * Method to get transpose of a matrix. It creates a new matrix to copy the
 * elements because the physical structure of the matrix may change as a
 * part of the transpose operation in case its not a square matrix.
 */
public int[][] transpose(int[][] mat) {
    if (mat == null)
        return null;

    int m = mat.length;
    int n = mat[0].length;
    int[][] matResult = new int[n][m];
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            matResult[j][i] = mat[i][j];
        }
    }
    return matResult;
}

/*
* Method to get the horizontal reflection of the matrix.
*/
public void horizontalReflection(int[][] mat) {
    int m = mat.length;
    int n = mat[0].length;
    int temp = 0;
    for (int i = 0; i < m / 2; i++) {
        for (int j = 0; j < n; j++) {
            temp = mat[i][j];
            mat[i][j] = mat[m - (i + 1)][j];
            mat[m - (i + 1)][j] = temp;
        }
    }
}

/*
 * Method to get the vertical reflection of the given matrix
*/
public void verticalReflection(int[][] mat) {
    int m = mat.length;
    int n = mat[0].length;
    int temp = 0;
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n/2; j++){
            temp = mat[i][j];
            mat[i][j] = mat[i][n-1-j];
            mat[i][n-1-j] = temp;
        }
    }
}

/*
* Utility method to print the matrix.
*/
public void printMatrix(int[][] mat) {
    int m = mat.length;
    int n = mat[0].length;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            System.out.print(mat[i][j] + "  ");
        }
        System.out.println();
    }
}

References:

  1. Rotate Image (From Life In Code)
  2. LeetCode Rotate Image旋转图像
  3. Matrix Rotation and Matrix Transpose

results matching ""

    No results matching ""