Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ccde2d0

Browse files
authored
Merge pull request neetcode-gh#1230 from ElminD/patch-1
Update 49-Java
2 parents 874a418 + 651d3fc commit ccde2d0

File tree

1 file changed

+24
-26
lines changed

1 file changed

+24
-26
lines changed

java/48-Rotate-Image.java

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,33 @@
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-
71
class Solution {
8-
92
public void rotate(int[][] matrix) {
10-
int N = matrix.length;
3+
int l = 0;
4+
int r = matrix.length - 1;
5+
6+
while ( l < r )
7+
{
8+
for(int i = 0; i < r - l; i++)
9+
{
10+
int top = l;
11+
int bottom = r;
12+
//save the topleft
13+
int topLeft = matrix[top][l + i];
1114

12-
transpose(matrix, N);
13-
reverse(matrix, N);
14-
}
15+
//move bottom left into top left
16+
matrix[top][l + i] = matrix[bottom - i][l];
1517

16-
void transpose(int[][] matrix, int n) {
17-
for (int i = 0; i < n; i++) {
18-
for (int j = i + 1; j < n; j++) {
19-
int temp = matrix[j][i];
20-
matrix[j][i] = matrix[i][j];
21-
matrix[i][j] = temp;
22-
}
23-
}
24-
}
18+
// move bottom right into bottom left
19+
matrix[bottom - i][l] = matrix[bottom][r - i];
20+
21+
// move top right into bottom right
22+
matrix[bottom][r - i] = matrix[top + i][r];
2523

26-
void reverse(int[][] matrix, int n) {
27-
for (int i = 0; i < n; i++) {
28-
for (int j = 0; j < n / 2; j++) {
29-
int temp = matrix[i][j];
30-
matrix[i][j] = matrix[i][n - 1 - j];
31-
matrix[i][n - 1 - j] = temp;
24+
// move top left into top right
25+
matrix[top + i][r] = topLeft;
26+
3227
}
28+
29+
r -= 1;
30+
l += 1;
3331
}
3432
}
3533
}

0 commit comments

Comments
 (0)