-
Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathRotateMatrixBy90Degrees.java
73 lines (64 loc) · 1.71 KB
/
RotateMatrixBy90Degrees.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.thealgorithms.matrix;
import java.util.Scanner;
/**
* Given a matrix of size n x n We have to rotate this matrix by 90 Degree Here
* is the algorithm for this problem .
*/
final class RotateMatrixBy90Degrees {
private RotateMatrixBy90Degrees() {
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int[][] arr = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = sc.nextInt();
}
}
Rotate.rotate(arr);
printMatrix(arr);
}
sc.close();
}
static void printMatrix(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println("");
}
}
}
/**
* Class containing the algo to roate matrix by 90 degree
*/
final class Rotate {
private Rotate() {
}
static void rotate(int[][] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i > j) {
int temp = a[i][j];
a[i][j] = a[j][i];
a[j][i] = temp;
}
}
}
int i = 0;
int k = n - 1;
while (i < k) {
for (int j = 0; j < n; j++) {
int temp = a[i][j];
a[i][j] = a[k][j];
a[k][j] = temp;
}
i++;
k--;
}
}
}