Skip to content

Commit 4d6d9f5

Browse files
Merge pull request #582 from priyashuu/rotate
Add RotateImage algorithm implementation in Java
2 parents 6bd007f + ada24ea commit 4d6d9f5

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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

Comments
 (0)