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数组中的查找问题咯,我觉得接下俩的四个问题主要训练的还是分而治之的思维方式。
相关文章推荐
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例
- PHP实现克鲁斯卡尔算法实例解析
- php使用Image Magick将PDF文件转换为JPG文件的方法