-
Notifications
You must be signed in to change notification settings - Fork 82
/
RotateMatrix.java
55 lines (45 loc) · 1.24 KB
/
RotateMatrix.java
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import java.util.Scanner;
public class RotateMatrix {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[][] matrix= new int[n][n];
for (int i=0 ; i<n ; i++){
for (int j= 0 ; j<n ; j++){
matrix[i][j]= s.nextInt();
}
}
rotate(matrix);
display(matrix);
}
public static void rotate(int[][] arr){
int n= arr.length;
//transpose
for (int i=0 ; i<n ; i++){
for (int j=0 ; j<i ; j++){
int temp= arr[j][i];
arr[j][i]= arr[i][j];
arr[i][j]= temp;
}
}
for(int i=0 ; i<n ; i++){
int p=0;
int q= arr[0].length - 1;
while (p <= q){
int temp= arr[i][p];
arr[i][p]= arr[i][q];
arr[i][q]= temp;
p++;
q--;
}
}
}
private static void display(int[][] arr) {
for (int i=0 ; i<arr.length ; i++){
for (int j=0 ; j<arr.length ; j++){
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}