Last active
October 8, 2017 22:34
-
-
Save shailrshah/ddc39dba4b2a6ba1b6745cb70ad1d544 to your computer and use it in GitHub Desktop.
2D Matrix Clockwise Rotation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Created by shail on 4/10/17. | |
*/ | |
class MatRotate { | |
static void toString(int[][]a, String message) { | |
System.out.println(message); | |
for(int i = 0; i < a.length; i++){ | |
for(int j = 0; j < a[0].length; j++) | |
System.out.print(a[i][j]); | |
System.out.println(); | |
} | |
} | |
static int[][] rotateRectangleMatrix(int a[][], boolean clockwise) { | |
int col = a.length; | |
int row = a[0].length; | |
int[][] r = new int[row][col]; | |
for(int x = 0; x < row; x++) | |
for(int y = 0; y < col; y++) | |
r[x][y] = clockwise ? a[col-1-y][x] : a[y][row-1-x]; | |
return r; | |
} | |
static int[][] transpose(int[][] a) { | |
for(int i = 0; i < a.length; i++) | |
for(int j = 0; j < i; j++) { | |
int temp = a[i][j]; | |
a[i][j] = a[j][i]; | |
a[j][i] = temp; | |
} | |
return a; | |
} | |
static int[][] reverseEachRow(int[][] a) { | |
int n = a.length; | |
int m = a[0].length; | |
for(int i = 0; i < n; i++) | |
for(int j = 0; j < m/2; j++){ | |
int temp = a[i][j]; | |
a[i][j] = a[i][m-1-j]; | |
a[i][m-1-j] = temp; | |
} | |
return a; | |
} | |
static int[][] reverseEachCol(int[][] a) { | |
int n = a.length; | |
int m = a[0].length; | |
for(int i = 0; i < n/2; i++) | |
for(int j = 0; j < m; j++) { | |
int temp = a[i][j]; | |
a[i][j] = a[n-1-i][j]; | |
a[n-1-i][j] = temp; | |
} | |
return a; | |
} | |
static int[][] rotateSquareMatrix(int[][] a, boolean clockwise) { | |
a = transpose(a); | |
return clockwise ? reverseEachRow(a) : reverseEachCol(a); | |
} | |
static int[][] rotate(int[][] a, boolean clockwise){ | |
return a.length == a[0].length ? rotateSquareMatrix(a, clockwise) : rotateRectangleMatrix(a, clockwise); | |
} | |
public static void main(String[] args) { | |
int[][] a = {{1,2,3},{4, 5, 6},{7, 8, 9}}; | |
toString(a, "Square Matrix, Original"); | |
System.out.println(); | |
toString(rotate(a, true), "Square Matrix, Rotated clockwise"); | |
System.out.println(); | |
toString(rotate(a, false), "Square Matrix, Rotated anti-clockwise"); | |
System.out.println(); | |
int[][] b = {{1, 2}, {3, 4}, {5, 6}}; | |
toString(b, "Rectangle Matrix, Original"); | |
System.out.println(); | |
toString(rotate(b, true), "Rectangle Matrix, Rotated clockwise"); | |
System.out.println(); | |
toString(rotate(b, false), "Rectangle Matrix, Rotated anti-clockwise"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment