# Java solutions - In Place and Out Place, with comments

• ``````public class Solution {
public void rotate(int[][] matrix) {
//    	rotate_outPlace(matrix);
rotate_inPlace(matrix);
}

public void rotate_inPlace(int[][] matrix) {
if(matrix==null || matrix.length==0) return;
final int N = matrix.length;
int temp=0;
// transpose
for(int i=0; i<N; i++){
for(int j=i; j<N; j++){
temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
// exchange left columns and right columns
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;
}
}
}

public void rotate_outPlace(int[][] matrix) {
if(matrix==null || matrix.length==0) return;
final int N = matrix.length;
int[][] res = new int[N][N];
int i=0, j=0, row=0, range=matrix.length, len=0;
while(range>0){
i=j=row;
len=row+range-1;
if(range == 1) {
res[i][j] = matrix[i][j];
break;
}
//top->right
for(;j<len;j++){
res[j][row+len-i] = matrix[i][j];
}
//right->bottom
for(;i<len;i++){
res[j][row+len-i] = matrix[i][j];
}
//bottom->left
for(;j>row;j--){
res[j][row+len-i] = matrix[i][j];
}
//left->top;
for(;i>row;i--){
res[j][row+len-i] = matrix[i][j];
}
//next round
row++;
range-=2;
}
for(i=0; i<N; i++)
for(j=0; j<N; j++)
matrix[i][j] = res[i][j];
}

}

``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.