您的位置:首页 > 编程语言 > C语言/C++

Leetcode Rotate Image

2015-10-23 08:26 489 查看
Leetcode Rotate Image 解决方法,本方法通过把一个矩阵分割成不同的环,然后对很一个环进行旋转,从而解决旋转问题,相关cpp代码,以及测试如下:

#include<iostream>
#include<vector>

using namespace std;
// In order to rotate the matrix in place, we make each cycle as a turn.
class Solution {
public:
void rotate(vector<vector<int> >& matrix) {
if (matrix.size() == 0) {
return;
}
// The square edge length of each turn.
int length = matrix.size() % 2 == 0? 0: 1;
// The start position of each rotate.
int start = matrix.size() / 2 - 1;
int temp;
for (; start >= 0; start --) {
for (int i = 0; i <= length; i ++) {
// Move the conrespond element to the proper position.
temp = matrix[start][start + i];
matrix[start][start + i] = matrix[start + length - i + 1][start];
matrix[start + length - i + 1][start] = matrix[start + length + 1][start + length - i + 1];
matrix[start + length + 1][start + length - i + 1] = matrix[start + i][start + length + 1];
matrix[start + i][start + length + 1] = temp;
}
// Everty turn the edge increase length by 2.
length += 2;
}
}
};

int main(int argc, char* argv[]) {
Solution so;
vector<vector<int> > test(5, vector<int>(5, 1));
test[0][0] = 0;
test[0][3] = 0;
test[2][0] = 0;
test[0][1] = 0;
test[1][2] = 3;
test[4][0] = 0;
test[4][2] = 5;
so.rotate(test);
cout<<"result: "<<endl;
for (int i = 0; i < test.size(); i ++) {
for (int j = 0; j < test[0].size(); j ++) {
cout<<test[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode cpp