|
| 1 | +/* |
| 2 | + * Algorithm Name:Rotate Image . |
| 3 | + * Programming Language: Java |
| 4 | + * Category: Array ,matrix |
| 5 | + * Difficulty Level: Medium |
| 6 | + * |
| 7 | + * Author: Priya Rani |
| 8 | + * |
| 9 | + * Algorithm Description: You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). |
| 10 | +
|
| 11 | + 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. |
| 12 | +
|
| 13 | + |
| 14 | +* Time Complexity: O(n²) Each element is visited once during transpose and once during row reversal |
| 15 | +* Space Complexity: O(1) Rotation is done in-place without using extra data structures |
| 16 | +*/ |
| 17 | +import java.util.*; |
| 18 | + |
| 19 | +public class RotateImage { |
| 20 | + public void rotate(int[][] matrix) { |
| 21 | + int n = matrix.length; |
| 22 | + |
| 23 | + for (int i = 0; i < n; i++) { |
| 24 | + for (int j = i + 1; j < n; j++) { |
| 25 | + int temp = matrix[i][j]; |
| 26 | + matrix[i][j] = matrix[j][i]; |
| 27 | + matrix[j][i] = temp; |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + for (int i = 0; i < n; i++) { |
| 32 | + for (int j = 0; j < n / 2; j++) { |
| 33 | + int temp = matrix[i][j]; |
| 34 | + matrix[i][j] = matrix[i][n - 1 - j]; |
| 35 | + matrix[i][n - 1 - j] = temp; |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + public static void main(String[] args) { |
| 41 | + RotateImage solution = new RotateImage(); |
| 42 | + |
| 43 | + int[][] matrix = { |
| 44 | + {1, 2, 3}, |
| 45 | + {4, 5, 6}, |
| 46 | + {7, 8, 9} |
| 47 | + }; |
| 48 | + |
| 49 | + solution.rotate(matrix); |
| 50 | + |
| 51 | + |
| 52 | + for (int[] row : matrix) { |
| 53 | + System.out.println(Arrays.toString(row)); |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments