Problem

Rotate Image

Approach

Find the pattern between old image and new image. The rule is that for the coordinate(x, y), it would be updated by the position(n - 1 - y, x).

Code

class Solution {
    public void rotate(int[][] matrix) {
        int N = matrix.length;
        if(N == 0){
            return ;
        }
        int m = 0, n = 0;
        if(N % 2 == 0){
            m = N / 2;
            n = N / 2;
        } else {
            m = N / 2;
            n = N / 2 + 1;
        }
        // we just need to go through a quarter of the image to finish the whole rotation.
        for(int i = 0; i < m; i ++){
            for(int j = 0; j < n; j ++){
                int x1 = i, y1 = j, x2 = N - 1 - y1, y2 = x1;
                int temp = matrix[x2][y2];
                for(int k = 0; k < 4; k ++){
                    int temp2 = matrix[x1][y1];
                    //System.out.printf("%d, %d[%d] -> %d, %d[%d]\n", x2, y2, temp, x1, y1, temp2);
                    matrix[x1][y1] = temp;
                    temp = temp2;
                    x2 = x1; y2 = y1;
                    x1 = y2; y1 = N - 1 - x2;
                }
            }
        }
    }
}