每日算法37:Rotate Image (图像旋转)
2015-09-30 12:49
387 查看
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?
原地图像顺时针旋转90度。由于要求空间复杂度是常数,因此应该迭代旋转操作。
![](http://img.blog.csdn.net/20140629215716234?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveWFwaWFuOA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
以下是网友给出的还有一种方案:
![](http://img.blog.csdn.net/20140629215915656?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveWFwaWFuOA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
原地图像顺时针旋转90度。由于要求空间复杂度是常数,因此应该迭代旋转操作。
class Solution { public: void rotate(vector<vector<int> > &matrix) { int n = matrix.size(); int layers = n/2;//图像旋转的圈数 for(int layer = 0;layer < layers;layer++)//每次循环一层,右青色到紫色 for(int i = layer;i<n-1-layer;i++)//每次可以交换四个元素的位置 { int temp = matrix[i][layer];//不清楚绘图举例就可以 matrix[i][layer] = matrix[n-1-layer][i]; matrix[n-1-layer][i] = matrix[n-1-i][n-1-layer]; matrix[n-1-i][n-1-layer] = matrix[layer][n-1-i]; matrix[layer][n-1-i] = temp; } } };
以下是网友给出的还有一种方案:
class Solution { public: void rotate(vector<vector<int> > &matrix) { int i,j,temp; int n=matrix.size(); // 沿着副对角线反转 for (int i = 0; i < n; ++i) { for (int j = 0; j < n - i; ++j) { temp = matrix[i][j]; matrix[i][j] = matrix[n - 1 - j][n - 1 - i]; matrix[n - 1 - j][n - 1 - i] = temp; } } // 沿着水平中线反转 for (int i = 0; i < n / 2; ++i){ for (int j = 0; j < n; ++j) { temp = matrix[i][j]; matrix[i][j] = matrix[n - 1 - i][j]; matrix[n - 1 - i][j] = temp; } } } };
相关文章推荐
- ocp-v13-077
- ocp-v13-076
- ocp-v13-075
- OpenCL C Built-IN Functions
- ocp-v13-074
- 简单的学生信息处理程序实现
- 项目范围管理论文的提纲
- ocp-v13-073
- ocp-v13-072
- 程序员在互联网公司和行业软件公司工作,有什么区别?
- ocp-v13-071
- jQuery.qrcode.js客户端生成二维码,支持中文并且可以生成LOGO
- GestureRecognizer手势
- 测试网址
- DNS正反解析及主从同步的实现
- 无主之地1
- 已知两个链表 la和 lb,其元素值递增排序。编程将la和lb合并成一个递减有序(相同值元素只保留一个)的链表lc。(北方名校经典试题) 本题选做
- POJ 2376 Cleaning Shifts(区间覆盖问题)
- 《Autotools - GNU Autoconf, Automake与Libtool实践者指南》第三章<用Autoconf配置你的项目>
- jQuery源码学习 之 get与eq的区别