Leetcode 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?


解题思路:

将每个[i, j]对应旋转对称的四个点的坐标算出来,然后pixel by pixel的旋转。

公式:matrix[i][j] = matrix[n-1-j][i]   i 表示从左到右,j 表示从右到左。

注意当n是奇数时,比如5,要转换到第3列/行,因此 j < Math.ceil((double) n / 2)


Java code:

public class Solution {
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        //matrix[i][j] = matrix[n-1-j][i]
        for(int i = 0; i < n/2; i++) {
            for(int j = 0; j < Math.ceil((double)n/2); j++){
                int temp = matrix[i][j];
                matrix[i][j] = matrix[n-1-j][i];
                matrix[n-1-j][i] = matrix[n-1-i][n-1-j];
                matrix[n-1-i][n-1-j] = matrix[j][n-1-i];
                matrix[j][n-1-i] = temp;
            }
        }
    }
}

Reference:

1. http://www.programcreek.com/2013/01/leetcode-rotate-image-java/

2. http://www.cnblogs.com/springfor/p/3886487.html

原文地址:https://www.cnblogs.com/anne-vista/p/4961843.html