└── rotate matrix 90 degree /rotate matrix 90 degree: -------------------------------------------------------------------------------- 1 | 2 | public class RotateMatrix { 3 | public static void main(String[] args) { 4 | int[][] matrix = { 5 | {1, 2, 3}, 6 | {4, 5, 6}, 7 | {7, 8, 9} 8 | }; 9 | 10 | rotate(matrix); 11 | 12 | System.out.println("Rotated Matrix:"); 13 | printMatrix(matrix); 14 | } 15 | 16 | public static void rotate(int[][] matrix) { 17 | // Transpose the matrix 18 | int n = matrix.length; 19 | for (int i = 0; i < n; i++) { 20 | for (int j = i; j < n; j++) { 21 | int temp = matrix[i][j]; 22 | matrix[i][j] = matrix[j][i]; 23 | matrix[j][i] = temp; 24 | } 25 | } 26 | 27 | // Reverse each row 28 | for (int i = 0; i < n; i++) { 29 | int left = 0; 30 | int right = n - 1; 31 | while (left < right) { 32 | int temp = matrix[i][left]; 33 | matrix[i][left] = matrix[i][right]; 34 | matrix[i][right] = temp; 35 | left++; 36 | right--; 37 | } 38 | } 39 | } 40 | 41 | public static void printMatrix(int[][] matrix) { 42 | for (int i = 0; i < matrix.length; i++) { 43 | for (int j = 0; j < matrix[0].length; j++) { 44 | System.out.print(matrix[i][j] + " "); 45 | } 46 | System.out.println(); 47 | } 48 | } 49 | } 50 | 51 | 52 | Output: 53 | 54 | Rotated Matrix: 55 | 7 4 1 56 | 8 5 2 57 | 9 6 3 58 | --------------------------------------------------------------------------------