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 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- CPP 虚函数、虚函数表及虚拟继承(转)
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- Deploying Control Plane Policing
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解