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

 

解题思路:

In-place Solution

By using the relation "matrix[i][j] = matrix[n-1-j][i]", we can loop through the matrix.

 

代码如下:

 1 public void rotate(int[][] matrix) {  2     int n = matrix.length;  3     for (int i = 0; i < n / 2; i++) {  4         for (int j = 0; j < Math.ceil(((double) n) / 2.); j++) {  5             int temp = matrix[i][j];  6             matrix[i][j] = matrix[n-1-j][i];  7             matrix[n-1-j][i] = matrix[n-1-i][n-1-j];  8             matrix[n-1-i][n-1-j] = matrix[j][n-1-i];  9             matrix[j][n-1-i] = temp; 10  } 11  } 12 }

a=Math.ceil(((double) n) / 2. :
若 n=3, a=2.0;
若 n=4, a=2.0;
若 n=5, a=3.0;
若 n=6, a=3.0;

 

运行过程:

假设图像为

1,2,3           旋转后为:          7,4,1

4,5,6                                   8,5,2

7,8,9                                   9,6,3

 

i=0,j=0

temp=m[0][0]

m[0][0]=m[2][0]=7

m[2][0]=m[2][2]=9

m[2][2]=m[0][2]=3

m[0][2]=temp=1

 

i=0,j=1

temp=m[0][1]

m[0][1]=m[1][0]=4

m[1][0]=m[2][1]=8

m[2][1]=m[1][2]=6

m[1][2]=temp=2

 

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

你可能感兴趣的:(image)