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?
可以找规律 得出映射关系,(i,j)===>(j,n-1-j)
由于要in-place,不能直接新建矩阵,所以从外圈开始,一个个置换。
1 public class Solution { 2 public void rotate(int[][] matrix) { 3 int n = matrix[0].length -1; 4 for(int i = 0;i <= n - i;i++){ 5 for(int j = i;j <= n - i - 1;j++) 6 { 7 int tmp = matrix[j][n-i]; 8 matrix[j][n-i] = matrix[i][j]; 9 matrix[i][j] = matrix[n-j][i]; 10 matrix[n-j][i] = matrix[n-i][n-j]; 11 matrix[n-i][n-j] = tmp; 12 } 13 } 14 } 15 }