-
Notifications
You must be signed in to change notification settings - Fork 0
/
ArrayRotation.java
58 lines (44 loc) · 1.3 KB
/
ArrayRotation.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
/* This code is written for rotating 2d array 90 degrees */
import java.util.*;
public class ArrayRotation {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
int[][] arr = new int[a][b];
int[][] arr1 = new int[b][a];
int[][] arr2 = new int[b][a];
//input to the arr
for(int i=0; i<a; i++) {
for(int j = 0; j<b; j++) {
arr[i][j] = in.nextInt();
}
}
System.out.println("Rotated: ");
//converted from N x M --> M x N
for (int i = 0; i < a; i++) {
for (int j = b-1; j >=0 ; j--) {
arr1[j][i] = arr[i][j];
}
}
//inverse M x N array
for(int i = 0; i < b; i++) {
int start = 0;
int end = a-1;
while(start <= end) {
int temp = arr1[i][start];
arr2[i][start] = arr1[i][end];
arr2[i][end] = temp;
start++;
end--;
}
}
//output the M x N array
for (int i = 0; i < b; i++) {
for (int j = 0; j < a; j++) {
System.out.print(arr2[i][j] + " ");
}
System.out.println();
}
}
}