您的位置:首页 > 其它

*Rotate Image

2015-07-16 21:30 225 查看
题目

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.

代码如下:

 public void rotate(int[][] matrix) {
int n = matrix.length;
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;
}
}
}


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/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: