LeetCode-algorithms 48. Rotate Image
来源:互联网 发布:淘宝进货在哪里进 编辑:程序博客网 时间:2024/05/16 14:24
题目:
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?
思考:
由于题目要求是在矩阵本身上做操作,这里就要考虑转换后的位置关系。比如左上角的点要转换到右上角,右上角的转换到右下角,右下角的转换到左下角,
左下角的转换到左上角,如此一个循环,为一个从“左上角点”出发的一个基本转换的循环。因此可以看到,这里对于每一个角落的操作都是同一的,都是转换至下一个位置。
因此可以把整幅图片平均分成4分,这样只需要遍历从右上角图案出发的循环即可完成整幅图像的转换,这里一次循环的位置变换为:
[i][j] = [n-1-j][i]
[n-1-j][i] = [n-1-i][n-1-j]
[n-1-i][n-1-j] = [j][n-1-i]
[j][n-1-i] = [i][j]
值得注意的是,当N为奇数时,一块左上角图案的大小为(n/2,n/2+1),这样就不会重复转换
代码:
class Solution(object):def rotate(self, matrix):for i in range(len(matrix) /2):for j in range(len(matrix) /2+len(matrix)%2):first = matrix[i][j]matrix[i][j] = matrix[len(matrix)-1-j][i]matrix[len(matrix)-1-j][i] = matrix[len(matrix)-1-i][len(matrix)-1-j]matrix[len(matrix)-1-i][len(matrix)-1-j] = matrix[j][len(matrix)-1-i]matrix[j][len(matrix)-1-i] = first
结果:
0 0
- LeetCode-algorithms 48. Rotate Image
- Algorithms—48.Rotate Image
- [LeetCode]48.Rotate Image
- LeetCode 48. Rotate Image
- LeetCode 48.Rotate Image
- LeetCode --- 48. Rotate Image
- [Leetcode] 48. Rotate Image
- [leetcode] 48. Rotate Image
- Leetcode 48. Rotate Image
- 48. Rotate Image LeetCode
- [LeetCode]48. Rotate Image
- leetcode 48. Rotate Image
- Leetcode 48. Rotate Image
- LeetCode 48. Rotate Image
- LeetCode *** 48. Rotate Image
- [LeetCode]48. Rotate Image
- LeetCode 48. Rotate Image
- LeetCode-48.Rotate Image
- java内存配置详解
- “Beyond Compare 许可证密钥被撤销” 的解决办法
- 《ACM程序设计》书中题目X 第二十四题 电话号码
- HTML中form表单里的get和post的区别
- [编程题] 好多鱼!(牛客网)
- LeetCode-algorithms 48. Rotate Image
- 进程和线程的最大区别
- Python_06
- keytool Android签名工具
- 百度地图API(6)调用绘图api绘制几何图形覆盖物
- 驾驭<hr />标签
- 【目标检测】OpenCV中dnn模块的SSD demo运行
- 数组——二维数组中的查找
- android中canvas.drawArc的弧度问题