48 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?
Analysis
Solution 1
public void rotate(int[][] matrix) {
int rowLength = matrix.length;
int colLength = matrix[0].length;
int[][] temp = new int[rowLength][colLength];
int newRow, newCol;
//copy
for(int row=0; row<rowLength; row++) {
for(int col=0; col<colLength; col++) {
temp[row][col] = matrix[row][col];
}
}
for(int row=0; row<rowLength; row++) {
for(int col=0; col<colLength; col++) {
newRow = col;
newCol = colLength - 1 - row;
matrix[newRow][newCol] = temp[row][col];
}
}
}
Follow up: Solution 2
public void rotate(int[][] matrix) {
int rowLength = matrix.length;
int colLength = matrix[0].length;
int maxRow, maxCol;
if(rowLength%2 == 0) {
maxRow = rowLength/2;
maxCol = colLength/2;
}else{
maxRow = rowLength/2;
maxCol = colLength/2 + 1;
}
int tempRow, tempCol;
int newRow=0;
int newCol=0;
int[] temp = new int[4];
for(int row=0; row<maxRow; row++) {
for(int col=0; col<maxCol; col++) {
for(int i=0; i<4; i++) {
if(i==0) {
tempRow = row;
tempCol = col;
}
else{
tempRow = newRow;
tempCol = newCol;
}
newRow = tempCol;
newCol = colLength -1 -tempRow;
temp[i] = matrix[newRow][newCol];
if(i==0){
matrix[newRow][newCol] = matrix[tempRow][tempCol];
}else{
matrix[newRow][newCol] = temp[i-1];
}
}
}
}
}