You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
public class Solution {
public void rotate(int[][] matrix) {
int n = matrix.length;
for(int layer = 0; layer < n/2; layer++){
int temp = 0;
for(int i=layer; i<=n-2-layer; i++){
//matrix[layer][i]; // top
//matrix[i][n-1-layer]; // right
//matrix[n-1-layer][n-1-i]; // bottom
//matrix[n-1-i][layer]; //left
// temp = top
temp = matrix[layer][i];
// top = left
matrix[layer][i] = matrix[n-1-i][layer];
// left = bottom
matrix[n-1-i][layer] = matrix[n-1-layer][n-1-i];
// bottom = right
matrix[n-1-layer][n-1-i] = matrix[i][n-1-layer];
// right = temp
matrix[i][n-1-layer] = temp;
}
}
}
}

No comments:
Post a Comment