[LeetCode] Rotate Image n-by-n矩阵顺时针旋转
2014-11-28 13:56
513 查看
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?
Hide Tags
Array
一题严格的数组逻辑操作问题,考虑认真就好,思路:
如上表,一共有两圈,对于n 来说,圈数为(n+1)/2,从外圈到内圈,转换了一圈后到下一圈。
我写的代码用了长度len ,其实写j=i 会方便很多。
需要计算好下标,有个简单的确认,一次转换中的4个数,不相邻的两个数的对应下标和为定值(n-1),例如一个是<i,j>,另一个就是<n-1 -i,n-1 -j>,利用这个规律其实只要确认两个就行。
代码如下:
View Code
Rotate the image by 90 degrees (clockwise).
Follow up:
Could you do this in-place?
Hide Tags
Array
一题严格的数组逻辑操作问题,考虑认真就好,思路:
1 | 2 | 3 | 1 |
3 | 4 | 4 | 2 |
2 | 4 | 4 | 3 |
1 | 3 | 2 | 1 |
我写的代码用了长度len ,其实写j=i 会方便很多。
需要计算好下标,有个简单的确认,一次转换中的4个数,不相邻的两个数的对应下标和为定值(n-1),例如一个是<i,j>,另一个就是<n-1 -i,n-1 -j>,利用这个规律其实只要确认两个就行。
代码如下:
#include <iostream> #include <vector> #include <iterator> using namespace std; class Solution { public: void rotate(vector<vector<int> > &matrix) { int n =matrix.size(); if(n<2) return ; for(int i=0;i<(n+1)/2;i++){ for(int len=0;len<=n-2*(i+1);len++){ int temp = matrix[i][i+len]; matrix[i][i+len] = matrix[n-1-i-len][i]; matrix[n-1-i-len][i] = matrix[n-1-i][n-1-i-len]; matrix[n-1-i][n-1-i-len] = matrix[i+len][n-i-1]; matrix[i+len][n-i-1] = temp; } } } }; int main() { vector<vector<int> > matrix; vector<int> tempm; int cnt =1; for(int i=1;i<9;i++){ for(int j=1;j<9;j++) tempm.push_back(cnt++); matrix.push_back(tempm); tempm.clear(); } Solution sol; sol.rotate(matrix); for(int i=0;i<matrix.size();i++){ copy(matrix[i].begin(),matrix[i].end(),ostream_iterator<int>(cout," ")); cout<<endl; } return 0; }
View Code
相关文章推荐
- LeetCode-Rotate Image-图像旋转-矩阵元素操作
- [leetcode 48] Rotate Image--------矩阵旋转90度
- LeetCode——Rotate Image(二维数组顺时针旋转90度)
- 方形矩阵顺时针旋转90度 Rotate Image
- leetcode 48. Rotate Image 矩阵旋转
- 矩阵旋转系列之【LeetCode】Rotate Image && 【九度】题目1164:旋转矩阵
- LeetCode-48-Rotate Image 矩阵旋转90
- LeetCode——Rotate Image(二维数组顺时针旋转90度)
- LeetCode Rotate Image(矩阵的旋转)
- LeetCode-----48. Rotate Image(二维矩阵旋转90度)
- [LeetCode] Rotate Image 旋转图像
- 【旋转矩阵】Rotate Image
- leetcode解题之48. Rotate Image java版(旋转图像)
- leetCode 48.Rotate Image (旋转图像) 解题思路和方法
- leetcode之图像旋转(Rotate Image)
- [LeetCode]27. Rotate Image图像旋转
- Leetcode:Rotate Image 旋转图片
- Leetcode刷题记——48. Rotate Image(旋转图像)
- [Leetcode] rotate image 旋转图片
- Rotate Image(二位数组顺时针旋转)