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?
Solution
This problem logic is easy, we have only to be careful with the position index. For instance,
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
We have marked in pink the elements that rotate for row 0, column 1.public class Solution {
public void rotate(int[][] matrix) {
for(int i=0; i<matrix.length/2; i++)
{
for (int j=i; j<(matrix.length-1-i); j++)
{
int temp = matrix[i][j];
matrix[i][j]=matrix[matrix.length-1-j][i];
matrix[matrix.length-1-j][i]= matrix[matrix.length-i-1][matrix.length-j-1];
matrix[matrix.length-i-1][matrix.length-j-1] = matrix[j][matrix.length-i-1];
matrix[j][matrix.length-i-1] = temp;
}
}
}
}
No comments :
Post a Comment