【LeetCode从零单刷】Rotate Image
2015-10-13 22:13
417 查看
题目:
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?
解答:
一开始想的很复杂,希望找到一个通式应对所有角度的旋转。所有的细节写在《【图像处理】基于OpenCV底层实现的图片旋转》。
其实没有必要,因为90度是非常特殊的一种旋转,可以直观上赋值:
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
vector<int> tmp(m, 0);
vector<vector<int>> ans(n, tmp);
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
{
ans[j][m-1 - i] = matrix[i][j];
}
matrix = ans;
return;
}
};
但仔细看题目要求:in-place(原地)。想了半天没想出来原地旋转的方法。直到看到巧妙做法:传送门。精粹就在下图中:
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;
}
}
}
};
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?
解答:
一开始想的很复杂,希望找到一个通式应对所有角度的旋转。所有的细节写在《【图像处理】基于OpenCV底层实现的图片旋转》。
其实没有必要,因为90度是非常特殊的一种旋转,可以直观上赋值:
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int m = matrix.size();
int n = matrix[0].size();
vector<int> tmp(m, 0);
vector<vector<int>> ans(n, tmp);
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
{
ans[j][m-1 - i] = matrix[i][j];
}
matrix = ans;
return;
}
};
但仔细看题目要求:in-place(原地)。想了半天没想出来原地旋转的方法。直到看到巧妙做法:传送门。精粹就在下图中:
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;
}
}
}
};
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性
- C++ Custom Control控件向父窗体发送对应的消息