*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.
代码如下:
运行过程:
假设图像为
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/
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/
相关文章推荐
- chapter18test4
- [Leetcode] Sort Colors
- uva 1252(状态压缩dp)
- 如何直接强制客户端刷新.js文件
- 如何将json数据传回前台
- Project Euler:Problem 68 Magic 5-gon ring
- Ant---下载,生成,编写
- 题目1190:大整数排序
- 关于传到PHP用PHP处理计算器和js做的计算器对比
- Oracle实践--PL/SQL表分区的基础
- python with原型
- 搭建金字塔
- day02--课后练习
- 菜鸟学linux
- 可展开的TextView
- 线段树专题
- instanceof和getClass()的区别
- HDU 1086You can Solve a Geometry Problem too(判断线段相交模板题)
- HDU 2571-----简单的DP
- 有效检查Java代码的工具:5款调试工具