Rotate Image
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?
public class Solution { public void rotate(int[][] matrix) { if(matrix == null) return; int n = matrix.length; // n * n matrix //int w = matrix[0].length; if(n < 2) return; // rule: i = j'; j = n-1 - i'; // that is: i' = n-1 -j; j' = i; // loop through 1/4 of the matrix // a | b // c | d // four parts // Math.ceil : returns the smallest integer >= a number. for(int i = 0; i < n/2; i++) { for(int j = 0; j < Math.ceil(((double)n)/2.0); j++) { int tmp = matrix[i][j]; // c -> a matrix[i][j] = matrix[n-1 - j][i]; // d -> c matrix[n-1 - j][i] = matrix[n-1 - i][n-1 - j]; // b -> d matrix[n-1 - i][n-1 - j] = matrix[j][n-1 - i]; // a -> b (tmp -> b) matrix[j][n-1 - i] = tmp; } } } }
No comments:
Post a Comment