|
| 1 | +[](https://github.com/LeetCode-in-Net/LeetCode-in-Net) |
| 2 | +[](https://github.com/LeetCode-in-Net/LeetCode-in-Net/fork) |
| 3 | + |
| 4 | +## 48\. Rotate Image |
| 5 | + |
| 6 | +Medium |
| 7 | + |
| 8 | +You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise). |
| 9 | + |
| 10 | +You have to rotate the image [**in-place**](https://en.wikipedia.org/wiki/In-place_algorithm), which means you have to modify the input 2D matrix directly. **DO NOT** allocate another 2D matrix and do the rotation. |
| 11 | + |
| 12 | +**Example 1:** |
| 13 | + |
| 14 | + |
| 15 | + |
| 16 | +**Input:** matrix = \[\[1,2,3],[4,5,6],[7,8,9]] |
| 17 | + |
| 18 | +**Output:** [[7,4,1],[8,5,2],[9,6,3]] |
| 19 | + |
| 20 | +**Example 2:** |
| 21 | + |
| 22 | + |
| 23 | + |
| 24 | +**Input:** matrix = \[\[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] |
| 25 | + |
| 26 | +**Output:** [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] |
| 27 | + |
| 28 | +**Example 3:** |
| 29 | + |
| 30 | +**Input:** matrix = \[\[1]] |
| 31 | + |
| 32 | +**Output:** [[1]] |
| 33 | + |
| 34 | +**Example 4:** |
| 35 | + |
| 36 | +**Input:** matrix = \[\[1,2],[3,4]] |
| 37 | + |
| 38 | +**Output:** [[3,1],[4,2]] |
| 39 | + |
| 40 | +**Constraints:** |
| 41 | + |
| 42 | +* `matrix.length == n` |
| 43 | +* `matrix[i].length == n` |
| 44 | +* `1 <= n <= 20` |
| 45 | +* `-1000 <= matrix[i][j] <= 1000` |
| 46 | + |
| 47 | +## Solution |
| 48 | + |
| 49 | +```csharp |
| 50 | +public class Solution { |
| 51 | + public void Rotate(int[][] matrix) { |
| 52 | + (int height, int width) = (matrix.Length, matrix[0].Length); |
| 53 | + for (int row = 0; row < height - 1; row++) { |
| 54 | + for (int col = row + 1; col < width; col++) { |
| 55 | + (matrix[col][row], matrix[row][col]) = (matrix[row][col], matrix[col][row]); |
| 56 | + } |
| 57 | + } |
| 58 | + for (int col = 0; col < width / 2; col++) { |
| 59 | + int oppositeCol = width - 1 - col; |
| 60 | + for (int row = 0; row < height; row++) { |
| 61 | + (matrix[row][col], matrix[row][oppositeCol]) = (matrix[row][oppositeCol], matrix[row][col]); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | +} |
| 66 | +``` |
0 commit comments