48. 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?

思路: 选择n*n的矩阵. 写出翻转之前的坐标, 跟翻转之后的坐标, 原矩阵坐标等于翻转之后的矩阵坐标。

(i,j)…..(i, n-j)
. .
. .
(n-j,i)….(n-i,n-j)

翻转之后:
(n-j,i)…..(i,j)
. .
. .
(n-i,n-j)…(i, n-j)

public class Solution {
    public void rotate(int[][] matrix) {
        if (matrix == null || matrix[0] == null || matrix.length == 0 || matrix[0].length == 0)
            return;
        // flip
        int n = matrix.length - 1;
        for (int i = 0; i <= n/2; i++) {
            for (int j = 0; j < matrix.length /2 ; j++) {
                int tmp = matrix[i][j];
                matrix[i][j] = matrix[n-j][i];
                matrix[n-j][i]= matrix[n-i][n-j];
                matrix[n-i][n-j] = matrix[j][n-i];
                matrix[j][n-i] = tmp;
            }
        }

    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s