您的位置:首页 > 其它

Rotate Image

2015-07-22 00:17 337 查看

LeetCode中Image的rotate问题

  旋转一张图片,其实不难,但是也有点意思,上题咯~

  https://leetcode.com/problems/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的矩阵,你能顺时针将其旋转90度吗。追问:可以不使用额外的空间吗?

为题分析

  看到这个问题,让我想到了我在array的rotate那一题中的思路,把a送到该去的位置,然后将该位置上的元素送到它该去的位置,最后循环到起始位置,利用整个矩阵的中心,我只要先旋转整个第一行,然后第二行的2到n-1的元素,第三行的3到n-2的元素…

  如图:


  我们先旋转红色的元素,然后旋转黄色的元素,然后旋转蓝色的元素。比如对于A位置,将A送到B,B位置的送到C,C送到D,D送到A,这也是为什么第一行最后一个元素不需要进行旋转。

  上代码:

public void rotate(int[][] matrix) {
int length = matrix.length;
if(length < 2)
{
return;
}
double core = 0;
//对于n为基数或者偶数,计算旋转的中心坐标
core = length % 2 == 0 ? length/2 - 0.5 : length/2;

for(int i = 0; i < length/2; i++)
{
for(int j = i; j < length - i - 1; j++ )
{
rotate(matrix, i, j, core);
}
}
return;
}
//图中A-B-C-D的一次旋转操作,core是中心坐标,x和y是该店的横纵坐标
public void rotate(int[][] matrix, int x, int y, double core)
{
int temp = matrix[x][y];
double nextX = x;
double nextY = y;

for(int i = 0; i < 4; i++)
{
double tempY = nextY;
nextY = 2*core - nextX;
nextX = tempY;
int newTemp = matrix[(int)nextX][(int)nextY];
matrix[(int)nextX][(int)nextY] = temp;
temp = newTemp;
}
}


  这里面的坐标计算不太直观,自己画图分析分析吧,哈哈,接下来我们就要研究研究rotate数组中的查找问题咯,我觉得接下俩的四个问题主要训练的还是分而治之的思维方式。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode image rotate 算法