48. Rotate Image

LeetCode

Approach : Transpose and then reverse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
private void swap(int[][] arr,int i,int j){
int tmp=arr[i][j];
arr[i][j]=arr[j][i];
arr[j][i]=tmp;
}
private void transpose(int[][] matrix){
for(int i=0;i<matrix.length;i++){
for(int j=i;j<matrix[0].length;j++){
swap(matrix,i,j);
}
}
}
private void reverseRows(int[][] arr){
for(int[] row:arr){
int l=0,r=arr.length-1;
while(l<r){
int tmp=row[l];row[l]=row[r];row[r]=tmp;
l++;r--;
}
}
}
public void rotate(int[][] matrix) {
transpose(matrix);
reverseRows(matrix);
}
}

0%