title :
You are given a n x n 2D matrix representing an image.
Rotate the image by degrees (clockwise).
Follow up:
Could do this in-place?
Problem Solving Ideas:
In-place Solution
By using the relation "matrix[i][j] = Matrix[n-1-j][i]", we can loop through the matrix.
The code is as follows:
1 Public voidRotateint[] matrix) {2 intn =matrix.length;3 for(inti = 0; I <N/2; i++) {4 for(intj = 0; J <Math.ceil (((double) n)/2.); J + +) {5 inttemp =Matrix[i][j];6MATRIX[I][J] = matrix[n-1-J] [i];7Matrix[n-1-j][i] = matrix[n-1-i][n-1-j];8MATRIX[N-1-I][N-1-J] = matrix[j][n-1-i];9Matrix[j][n-1-i] =temp;Ten } One } A}
A=math.ceil (((double) n)/2.
If n=3, a=2.0;
If n=4, a=2.0;
If n=5, a=3.0;
If n=6, a=3.0;
Run the process:
Suppose the image is
After the rotation: 7,4,1
4,5,6 8,5,2
7,8,9 9,6,3
I=0,j=0
TEMP=M[0][0]
M[0][0]=m[2][0]=7
M[2][0]=m[2][2]=9
M[2][2]=m[0][2]=3
M[0][2]=temp=1
I=0,j=1
TEMP=M[0][1]
M[0][1]=m[1][0]=4
M[1][0]=m[2][1]=8
M[2][1]=m[1][2]=6
m[1][2]=temp=2
reference:http://www.programcreek.com/2013/01/leetcode-rotate-image-java/
*rotate Image