Skip to content

Commit b838aac

Browse files
authored
Merge pull request neetcode-gh#91 from vrindavan/main
48. Rotate Image Java Solution
2 parents acf09e6 + e363ce5 commit b838aac

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

java/48-Rotate-Image.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// Do note that this is for a sqaure matrix (NxN)
2+
// The process is to first transpose the matrix and then reverse it
3+
// Taking the first example: [[1,2,3],[4,5,6],[7,8,9]]
4+
// After Transpose: [[1,4,7],[2,5,8],[3,6,9]]
5+
// After Reversal: [[7,4,1],[8,5,2],[9,6,3]]
6+
7+
class Solution {
8+
public void rotate(int[][] matrix) {
9+
int N = matrix.length;
10+
11+
transpose(matrix, N);
12+
reverse(matrix, N);
13+
}
14+
15+
void transpose(int[][] matrix, int n) {
16+
for (int i = 0; i < n; i++) {
17+
for (int j = i + 1; j < n; j++) {
18+
int temp = matrix[j][i];
19+
matrix[j][i] = matrix[i][j];
20+
matrix[i][j] = temp;
21+
}
22+
}
23+
}
24+
25+
void reverse(int[][] matrix, int n) {
26+
for (int i = 0; i < n; i++) {
27+
for (int j = 0; j < n / 2; j++) {
28+
int temp = matrix[i][j];
29+
matrix[i][j] = matrix[i][n - 1 - j];
30+
matrix[i][n - 1 - j] = temp;
31+
}
32+
}
33+
}
34+
}

0 commit comments

Comments
 (0)