[Leetcode] Rotate Image
来源:互联网 发布:大型网络游排行榜2016 编辑:程序博客网 时间:2024/06/05 04:22
描述
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?
将一个二维
分析1
这是一道很经典的题目,比较简单的做法是先对矩阵转置,然后对矩阵进行水平翻转。
举一个例子说明:
1 2 3 1 4 7 7 4 14 5 6 ==> 2 5 8 ==> 8 5 27 8 9 3 6 9 9 6 3
代码如下。
代码1
class Solution {public: void rotate(vector<vector<int>>& matrix) { if (matrix.empty()) return; int n = matrix.size(); for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) swap(matrix[i][j], matrix[j][i]); } for (int i = 0; i < n; i++) reverse(matrix[i].begin(), matrix[i].end()); }};
分析2
还有一种方法是:每次操作对相应位置的四个数进行旋转,为此利用两条对角线将矩阵分成四部分,取上面一部分进行变换。
举例说明:
原矩阵 <1 4 13 16> <2 8 15 9>1 2 3 4 13 2 3 1 13 9 3 15 6 7 8 5 6 7 8 5 6 7 29 10 11 12 9 10 11 12 15 10 11 1213 14 15 16 16 14 15 4 16 14 8 4<3 12 14 5> <6 7 10 11>13 9 5 1 13 9 5 1 14 6 7 2 14 10 6 215 10 11 3 15 11 7 316 12 8 4 16 12 8 4
代码2
class Solution {public: void rotate(vector<vector<int>>& matrix) { if (matrix.empty()) return; int n = matrix.size(); for (int i = 0; i < n / 2; i++) { for (int j = i; j < n - 1 - i; j++) { int tmp = 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] = tmp; } } }};
0 0
- LeetCode: Rotate Image
- [Leetcode] Rotate Image
- LeetCode : Rotate Image
- [LeetCode] Rotate Image
- leetcode 67: Rotate Image
- [leetcode] Rotate Image
- [Leetcode] Rotate Image
- [LeetCode]Rotate Image
- LeetCode-Rotate Image
- [leetcode] Rotate Image
- LeetCode - Rotate Image
- leetcode之Rotate Image
- LeetCode - Rotate Image
- Leetcode: Rotate Image
- LeetCode:Rotate Image
- Leetcode: Rotate Image
- Leetcode Rotate Image
- leetcode Rotate Image
- MySQl里类似Oracle rownum的实现
- CASE WHEN的简单用法
- 笑看人生百态
- JQuery学习之操作类数组的工具方法_优就业
- transition和transform属性的区别
- [Leetcode] Rotate Image
- FFT的详细解释,相信你看了就明白了
- 织梦DedeCMS如何让文章列表实现“隔行换色”
- flex布局(二)--实例
- MySQL常用语句(六):纯数据的导出导入
- javascript学习基础要点(三)
- CentOS6.5搭建Dlib+OpenCV开发环境
- ubuntu16.04.1下安装KDE环境
- lua加载函数require和dofile