Published
- 2 min read
Rotate a matrix
**Rotate a matrix
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
- Transpose of a matrix ( row becomes column and column becomes rows)
- Reflect of a matrix, matrix reflect switches the leftmost column with rightmost column and move to next consecutive columns for switching
This is easier to code and understand as well, because the solution is neat and clean Transpose + Reflect
private void rotateImage1(int [][] image, int [][] copy) {
//in place, rotate the image by 90 degree
/**
* [[1, 2, 3] [7 4 1]
* 00 01 02 20 10 00
* [4, 5, 6] [8 5 2]
* 10 11 12 21 11 01
* [7, 8, 9] [9 6 3]
* 20 21 22 22 12 02 ]
*
* Transpose of matrix : rows become column and column becomes rows, put [i][j] with [j][i]
Reflect of a matrix : left column is changed with rightmost column, iterate till n/2, put [i][j] on [n-j-1]
*/
int [][] input = transposeOfAMatrix(image, image.length);
int [][] finalOutput = reflect(input, input.length);
}
private int[][] transposeOfAMatrix(int [][] input, int n) {
for (int i =0; i < n ; i++) {
for (int j =0; j < n; j++) {
System.out.println("("+ i +","+j+")");
System.out.println("("+ j +","+i+")");
System.out.println("*******");
int tmp = input[i][j];
input[j][i] = input[i][j];
input[i][j] = tmp;
}
}
return input;
}
//Reflect means switch left col with right col
/**
*/
private int[][] reflect(int [][] input, int n) {
for (int i =0; i < n ; i++) {
for (int j =0; j < n/2; j++) {
System.out.println("("+ i +","+j+")");
System.out.println("("+ j +","+i+")");
System.out.println("*******");
int tmp = input[i][j];
input[j][i] = input[i][n-j-1]; //n-j-1 means 4-0-1, 3, so 00 will be exchanged with 03
input[i][j] = tmp;
}
}
return input;
}