LeetCode-Rotate Image-图像旋转-矩阵元素操作
2014-10-20 20:24
555 查看
https://oj.leetcode.com/problems/rotate-image/
90度顺时针旋转一个矩阵。很容易联想到矩阵转置。但是矩阵转置是将第i行变成了第i列。而这个旋转的结果是要使第i行变成第n-i列。
所以在转置之后再将每一列调整到其应该在的地方即可。
还有一种方法是注意到每个元素的旋转是四个一组: (i,j) -->(j,n-i) --> (n-i,n-j)-->(n-j,i)-->(i,j)。如果能够准确的枚举出不重复的所有组,就能更快的旋转。
90度顺时针旋转一个矩阵。很容易联想到矩阵转置。但是矩阵转置是将第i行变成了第i列。而这个旋转的结果是要使第i行变成第n-i列。
所以在转置之后再将每一列调整到其应该在的地方即可。
还有一种方法是注意到每个元素的旋转是四个一组: (i,j) -->(j,n-i) --> (n-i,n-j)-->(n-j,i)-->(i,j)。如果能够准确的枚举出不重复的所有组,就能更快的旋转。
class Solution { public: void rotate(vector<vector<int> > &matrix) { int n=matrix.size(); for(int i=0;i<n;i++){ for(int j=i;j<n;j++){ swap(matrix[i][j],matrix[j][i]); } } for(int j=0;j<n/2;j++){ for(int i=0;i<n;i++){ swap(matrix[i][j],matrix[i][n-1-j]); } } } };
相关文章推荐
- LeetCode Rotate Image旋转图像
- LeetCode-48-Rotate Image 矩阵旋转90
- LeetCode 48. Rotate Image(旋转图像)
- [LeetCode] Rotate Image 旋转图像
- LeetCode Rotate Image旋转图像
- LeetCode-----48. Rotate Image(二维矩阵旋转90度)
- [LeetCode] Rotate Image 旋转图像
- [LeetCode] 48. Rotate Image 旋转图像
- leetcode解题之48. Rotate Image java版(旋转图像)
- leetcode 48. Rotate Image 矩阵旋转
- LeetCode--Rotate Image(旋转图像)Python
- [LeetCode] Rotate Image n-by-n矩阵顺时针旋转
- leetCode 48.Rotate Image (旋转图像) 解题思路和方法
- LeetCode Rotate Image(矩阵的旋转)
- [leetcode 48] Rotate Image--------矩阵旋转90度
- leetCode 48.Rotate Image (旋转图像) 解题思路和方法
- LeetCode 48 Rotate Image(2D图像旋转问题)
- leetcode之图像旋转(Rotate Image)
- Leetcode刷题记——48. Rotate Image(旋转图像)
- 矩阵旋转系列之【LeetCode】Rotate Image && 【九度】题目1164:旋转矩阵