Rotate Image
You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise). 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.
Examples
Constraints
n == matrix.length == matrix[i].length1 <= n <= 20-1000 <= matrix[i][j] <= 1000
Transpose and Reverse (Math Approach)
Approach
Rotating a matrix 90 degrees clockwise can be broken down into two simpler mathematical operations: 1. **Transpose the matrix**: Swap `matrix[i][j]` with `matrix[j][i]`. 2. **Reverse each row**: Swap `matrix[i][j]` with `matrix[i][n - 1 - j]`. This approach is easy to implement and modifies the matrix in-place.
Complexity Analysis
Time complexity is O(n^2) because we visit each element in the matrix of size n x n. Space complexity is O(1) since we do it in-place using only temporary variables for swapping.
class Solution { public void rotate(int[][] matrix) { int n = matrix.length; // Step 1: Transpose the matrix for (int i = 0; i < n; i++) { for (int j = i; j < n; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[j][i]; matrix[j][i] = temp; } } // Step 2: Reverse each row for (int i = 0; i < n; i++) { for (int j = 0; j < n / 2; j++) { int temp = matrix[i][j]; matrix[i][j] = matrix[i][n - 1 - j]; matrix[i][n - 1 - j] = temp; } } }}