LeetCode: 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?
import java.util.*;

public class RotateImage {
 
public static void rotateClockWise(int[][] matrix) {
/*
* clockwise rotate
* first reverse up to down, then swap the symmetry
* 1 2 3     7 8 9     7 4 1
* 4 5 6  => 4 5 6  => 8 5 2
* 7 8 9     1 2 3     9 6 3
*/
        //
        // 1.flip top down:
        // a[i, j] = a'[n-i-1, j]
        //
        // 2. flip diagonally from top left to bottom right
        // a[i, j] = a'[j, i]
     
        int n = matrix.length;
     
        if (n < 2) return;
     
        // 1.flip top down
        int upperRow = 0;
        int lowerRow = n-1;
        while (upperRow < lowerRow) {
            for (int i=0; i<n; i++) swap(matrix, upperRow, i, lowerRow, i);
            upperRow++;
            lowerRow--;
        }
     
        // 2. flip diagonally from top left to bottom right to swap the symmetry
        for (int i=0; i<n-1; i++) {
            for (int j=i+1; j<n; j++)
swap(matrix, i, j, j, i);
        }
     
    }
 
    public static void swap(int[][] matrix, int x1, int y1, int x2, int y2) {
        int temp = matrix[x1][y1];
        matrix[x1][y1] = matrix[x2][y2];
        matrix[x2][y2] = temp;
    }



/*
* anticlockwise rotate
* first reverse left to right, then swap the symmetry
* 1 2 3     3 2 1     3 6 9
* 4 5 6  => 6 5 4  => 2 5 8
* 7 8 9     9 8 7     1 4 7
*/
public static void rotateAntiClockWise(int[][] mat) {
//1. flip left to right
int n = mat.length;
int leftCol = 0, rightCol = n-1;
while(leftCol<rightCol){
for(int i = 0;i<n; i++){
swap(mat, i, leftCol, i, rightCol);
}
leftCol++;
rightCol--;
}


// 2. flip diagonally from top left to bottom right to swap the symmetry
        for (int i=0; i<n-1; i++) {
            for (int j=i+1; j<n; j++)
swap(mat, i, j, j, i);
        }

}

public static void printMatrix(int[][] mat){
for(int i=0;i<mat.length; i++){
System.out.println(Arrays.toString(mat[i]));
}
}

public static void main(String args[]){
int[][] mat = new int[3][3];
mat[0] = new int[]{1,2,3};
mat[1] = new int[]{4,5,6};
mat[2] = new int[]{7,8,9};
//rotateClockWise(mat);
//printMatrix(mat);
mat[0] = new int[]{1,2,3};
mat[1] = new int[]{4,5,6};
mat[2] = new int[]{7,8,9};
rotateAntiClockWise(mat);
printMatrix(mat);
}

}

No comments:

Post a Comment