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?
参考:
[解题思路]
如下图,首先沿逆对角线翻转一次,然后按x轴中线翻转一次。
1 public class Solution { 2 public void rotate(int[][] matrix) { 3 int len = matrix.length; 4 if(len == 0) 5 return; 6 7 for(int i = 0; i < len - 1; i++){ 8 for(int j = 0; j < len -i; j++){ 9 swap(matrix, i, j, len - 1 - j, len - 1 -i); 10 } 11 } 12 13 14 for(int i = 0; i < len / 2; i++){ 15 for(int j = 0; j < len; j++){ 16 swap(matrix, i, j, len - 1 -i, j); 17 } 18 } 19 } 20 21 public void swap(int[][] matrix, int i, int j, int m, int n){ 22 int tmp = matrix[i][j]; 23 matrix[i][j] = matrix[m][n]; 24 matrix[m][n] = tmp; 25 } 26 }
原文:http://www.cnblogs.com/RazerLu/p/3540015.html