|
| 1 | +/* |
| 2 | +Rotate Image |
| 3 | +============ |
| 4 | +
|
| 5 | +You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). |
| 6 | +
|
| 7 | +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. |
| 8 | +
|
| 9 | +Example 1: |
| 10 | +Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] |
| 11 | +Output: [[7,4,1],[8,5,2],[9,6,3]] |
| 12 | +
|
| 13 | +Example 2: |
| 14 | +Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] |
| 15 | +Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] |
| 16 | +
|
| 17 | +Example 3: |
| 18 | +Input: matrix = [[1]] |
| 19 | +Output: [[1]] |
| 20 | +
|
| 21 | +Example 4: |
| 22 | +Input: matrix = [[1,2],[3,4]] |
| 23 | +Output: [[3,1],[4,2]] |
| 24 | +
|
| 25 | +Constraints: |
| 26 | +matrix.length == n |
| 27 | +matrix[i].length == n |
| 28 | +1 <= n <= 20 |
| 29 | +-1000 <= matrix[i][j] <= 1000 |
| 30 | +*/ |
| 31 | + |
| 32 | +class Solution |
| 33 | +{ |
| 34 | +public: |
| 35 | + void rotate(vector<vector<int>> &matrix) |
| 36 | + { |
| 37 | + for (int i = 0; i < matrix.size(); ++i) |
| 38 | + { |
| 39 | + for (int j = i; j < matrix.size(); ++j) |
| 40 | + { |
| 41 | + swap(matrix[i][j], matrix[j][i]); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + for (int i = 0; i < matrix.size(); ++i) |
| 46 | + { |
| 47 | + for (int j = 0; j < matrix.size() / 2; ++j) |
| 48 | + { |
| 49 | + swap(matrix[i][j], matrix[i][matrix.size() - j - 1]); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | +}; |
0 commit comments