-
Notifications
You must be signed in to change notification settings - Fork 64
/
RotateMatrix.java
68 lines (56 loc) · 1.54 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
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.Scanner;
public class RotateMatrix {
int[][] matrix;
RotateMatrix(int[][] arr){
matrix = arr;
}
// rotate matrix clockwise by 90 deg
void rotate(){
// layer increments inwards
for(int layer = 0; matrix.length - layer*2 >= 1; layer++){
int length = matrix.length - layer*2; // length of current layer
// swap top with right
for (int i=layer; i<layer+length-1; i++){
int temp = matrix[layer][i]; // store top
matrix[layer][i] = matrix[i][layer+length-1];
matrix[i][layer+length-1] = temp;
}
// swap left with top
for (int i=layer+1; i<layer+length; i++){
int temp = matrix[i][layer]; // store left
matrix[i][layer] = matrix[layer][2*layer+length-1-i];
matrix[layer][2*layer+length-1-i] = temp;
}
// swap bot with left
for (int i=layer+1; i<layer+length; i++){
int temp = matrix[layer+length-1][i]; // store bot
matrix[layer+length-1][i] = matrix[i][layer];
matrix[i][layer] = temp;
}
}
}
void run(){
rotate();
printMatrix();
}
// prints a snapshot of matrix
void printMatrix(){
for (int i=0; i<matrix.length; i++){
for (int j=0; j<matrix.length; j++){
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
int[][] arr = new int[size][size];
// read in array
for (int i=0; i<size; i++)
for (int j=0; j<size; j++)
arr[i][j] = sc.nextInt();
(new RotateMatrix(arr)).run();
sc.close();
}
}