https://leetcode.com/problems/rotate-image/description/
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
Example 1:
Given input matrix = [ [1,2,3], [4,5,6], [7,8,9] ], rotate the input matrix in-place such that it becomes: [ [7,4,1], [8,5,2], [9,6,3] ]
Example 2:
Given input matrix = [ [ 5, 1, 9,11], [ 2, 4, 8,10], [13, 3, 6, 7], [15,14,12,16] ], rotate the input matrix in-place such that it becomes: [ [15,13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7,10,11] ]
- 数组简单题。对matrix,先上下反转,然后对折就行。如果是逆时针翻转的话,就先左右反转,再对折。
- reverse - C++ Reference
- http://www.cplusplus.com/reference/algorithm/reverse/
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 // 2 // main.cpp 3 // LeetCode 4 // 5 // Created by Hao on 2017/3/16. 6 // Copyright © 2017年 Hao. All rights reserved. 7 // 8 9 #include <iostream> 10 #include <vector> 11 using namespace std; 12 13 class Solution { 14 public: 15 void rotate(vector<vector<int>>& matrix) { 16 // reverse 17 reverse(matrix.begin(), matrix.end()); 18 19 // swap 20 for (int i = 0; i < matrix.size(); i ++) 21 for (int j = i + 1; j < matrix.size(); j ++) 22 swap(matrix[i][j], matrix[j][i]); 23 } 24 }; 25 26 int main(int argc, char* argv[]) 27 { 28 Solution testSolution; 29 30 vector<vector<vector<int>>> inputs = {{{1,2,3},{4,5,6},{7,8,9}}, {{5,1,9,11},{2,4,8,10},{13,3,6,7},{15,14,12,16}}}; 31 32 /* 33 1 2 3 34 4 5 6 35 7 8 9 36 37 ===> 38 39 7 4 1 40 8 5 2 41 9 6 3 42 43 5 1 9 11 44 2 4 8 10 45 13 3 6 7 46 15 14 12 16 47 48 ===> 49 50 15 13 2 5 51 14 3 4 1 52 12 6 8 9 53 16 7 10 11 54 */ 55 for (auto & input : inputs) { 56 for (auto & j : input) { 57 for (auto & k : j) 58 cout << k << " "; 59 cout << endl; 60 } 61 62 cout << " ===> " << endl; 63 64 testSolution.rotate(input); 65 66 for (auto & j : input) { 67 for (auto & k : j) 68 cout << k << " "; 69 cout << endl; 70 } 71 72 cout << endl; 73 } 74 75 return 0; 76 }