Matrix Rotation Implementaion in Java

Matrix Rotation Implementaion in Java

For matrix rotation, the simplest way is to use the formula shown in the following pictures:

matrix_clockwise_rotation

matrix_anti_clockwise_rotation

Take clockwise rotation as an example, here is the Java implementation of Matrix Rotation:

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
import java.util.Scanner;

public class MatrixRotation {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

int n = scan.nextInt();// n * n matrix
int[][] matrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i][j] = scan.nextInt();
}
}

int m = scan.nextInt();// rotate m times
int[][] rotatedMatrix = rotate(m, matrix);

for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(rotatedMatrix[i][j]);
System.out.print(" ");
}
System.out.println();
}
}

// Rotate matrix, 90 degrees clock wise.
public static int[][] rotate(int[][] matrix) {
int size = matrix[0].length;
int[][] result = new int[size][size];

for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
result[i][j] = matrix[size - 1 - j][i];
}
}
return result;
}

// Rotate matrix for many times.
public static int[][] rotate(int times, int[][] matrix) {
for (int i = 0; i < times; i++) {
matrix = rotate(matrix);
}
return matrix;
}
}