JavaAlgorithms/Others/RotateMatriceBy90Degree.java

61 lines
1.3 KiB
Java
Raw Normal View History

2021-09-21 02:49:24 +08:00
package Others;
/**
2021-09-21 02:50:09 +08:00
* Given a matrix of size n x n We have to rotate this matrix by 90 Degree Here is the algorithm for
* this problem .
2021-09-21 02:49:24 +08:00
*/
import java.util.*;
class Rotate_by_90_degree {
2021-09-21 02:50:09 +08:00
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
2021-09-21 02:49:24 +08:00
2021-09-21 02:50:09 +08:00
while (t-- > 0) {
int n = sc.nextInt();
int[][] arr = new int[n][n];
2021-09-21 02:49:24 +08:00
2021-09-21 02:50:09 +08:00
for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) arr[i][j] = sc.nextInt();
2021-09-21 02:49:24 +08:00
2021-09-21 02:50:09 +08:00
Rotate g = new Rotate();
g.rotate(arr);
printMatrix(arr);
2021-09-21 02:49:24 +08:00
}
2021-09-21 02:50:09 +08:00
sc.close();
}
2021-09-21 02:49:24 +08:00
2021-09-21 02:50:09 +08:00
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("");
2021-09-21 02:49:24 +08:00
}
2021-09-21 02:50:09 +08:00
}
2021-09-21 02:49:24 +08:00
}
2021-09-21 02:50:09 +08:00
/** Class containing the algo to roate matrix by 90 degree */
2021-09-21 02:49:24 +08:00
class Rotate {
2021-09-21 02:50:09 +08:00
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;
2021-09-21 02:49:24 +08:00
}
2021-09-21 02:50:09 +08:00
}
}
int i = 0, 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--;
2021-09-21 02:49:24 +08:00
}
2021-09-21 02:50:09 +08:00
}
2021-09-21 02:49:24 +08:00
}