Skip to content

Commit dc2d3d3

Browse files
Rotate matrix by 90 degree (TheAlgorithms#2316)
1 parent f981a2b commit dc2d3d3

1 file changed

Lines changed: 71 additions & 0 deletions

File tree

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package Others;
2+
3+
/**
4+
* Given a matrix of size n x n
5+
* We have to rotate this matrix by 90 Degree
6+
* Here is the algorithm for this problem .
7+
*
8+
*/
9+
10+
import java.util.*;
11+
12+
class Rotate_by_90_degree {
13+
public static void main(String[] args) {
14+
Scanner sc = new Scanner(System.in);
15+
int t = sc.nextInt();
16+
17+
while (t-- > 0) {
18+
int n = sc.nextInt();
19+
int[][] arr = new int[n][n];
20+
21+
for (int i = 0; i < n; i++)
22+
for (int j = 0; j < n; j++)
23+
arr[i][j] = sc.nextInt();
24+
25+
Rotate g = new Rotate();
26+
g.rotate(arr);
27+
printMatrix(arr);
28+
29+
}
30+
sc.close();
31+
}
32+
33+
static void printMatrix(int arr[][]) {
34+
for (int i = 0; i < arr.length; i++) {
35+
for (int j = 0; j < arr[0].length; j++)
36+
System.out.print(arr[i][j] + " ");
37+
System.out.println("");
38+
}
39+
}
40+
}
41+
42+
/**
43+
* Class containing the algo to roate matrix by 90 degree
44+
*/
45+
46+
class Rotate {
47+
static void rotate(int a[][]) {
48+
int n = a.length;
49+
for (int i = 0; i < n; i++) {
50+
for (int j = 0; j < n; j++) {
51+
if (i > j) {
52+
int temp = a[i][j];
53+
a[i][j] = a[j][i];
54+
a[j][i] = temp;
55+
}
56+
}
57+
}
58+
int i = 0, k = n - 1;
59+
while (i < k) {
60+
for (int j = 0; j < n; j++) {
61+
int temp = a[i][j];
62+
a[i][j] = a[k][j];
63+
a[k][j] = temp;
64+
}
65+
66+
i++;
67+
k--;
68+
}
69+
70+
}
71+
}

0 commit comments

Comments
 (0)