Skip to content

Instantly share code, notes, and snippets.

@junminstorage
Created July 19, 2015 01:17
Show Gist options
  • Save junminstorage/59ee3dbfb336d0e1c8bc to your computer and use it in GitHub Desktop.
Save junminstorage/59ee3dbfb336d0e1c8bc to your computer and use it in GitHub Desktop.
public static void rotateMatrixByElement(int[][] matrix){
int num = matrix.length;
for(int i=0; i<num/2; i++){
int start = matrix[i][i];
//shift up on column i
for(int row=i; row<num-i-1; row++){
matrix[row][i] = matrix[row+1][i];
}
//shift left on row num-i-1
for(int col=i; col<num-i-1; col++){
matrix[num-i-1][col] = matrix[num-i-1][col+1];
}
//shift down on column num-i-1
for(int row=num-i-1; row>i; row--){
matrix[row][num-i-1] = matrix[row-1][num-i-1];
}
//shift right on row i
for(int col=num-i-1; col>i; col--){
matrix[i][col] = matrix[i][col-1];
}
//the last one!
matrix[i][i+1] = start;
}
for(int i=0; i<num; i++)
System.out.println(Arrays.toString(matrix[i]));
}
@junminstorage
Copy link
Author

Rotate matrix

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment