-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy path2d-array rotation.java
116 lines (107 loc) · 3.04 KB
/
2d-array rotation.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int mat[][] = new int[n][m];
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[0].length; j++) {
mat[i][j] = sc.nextInt();
}
}
int s = sc.nextInt();
int r = sc.nextInt();
shellRotate(mat, s, r);
display(mat);
}
public static void shellRotate(int mat[][], int s, int r) {
int arr[] = fill1d(mat, s);
rotate(arr, r);
fill2d(mat, s, arr);
}
public static int[] fill1d(int mat[][], int s) {
int rmin = s - 1, cmin = s - 1, rmax = mat.length - s, cmax = mat[0].length - s;
int n = 2 * (rmax - rmin + cmax - cmin);
int arr[] = new int[n];
int idx = 0;
//left wall
for (int i = rmin; i <= rmax; i++) {
arr[idx] = mat[i][cmin];
idx++;
}
cmin++;
//bottom wall
for (int j = cmin; j <= cmax; j++) {
arr[idx] = mat[rmax][j];
idx++;
}
rmax--;
//right wall
for (int i = rmax; i >= rmin; i--) {
arr[idx] = mat[i][cmax];
idx++;
}
cmax--;
//top wall
for (int j = cmax; j >= cmin; j--) {
arr[idx] = mat[rmin][j];
idx++;
}
return arr;
}
public static void fill2d(int mat[][], int s, int arr[]) {
int rmin = s - 1, cmin = s - 1, rmax = mat.length - s, cmax = mat[0].length - s;
int idx = 0;
//left wall
for (int i = rmin; i <= rmax; i++) {
mat[i][cmin] = arr[idx];
idx++;
}
cmin++;
//bottom wall
for (int j = cmin; j <= cmax; j++) {
mat[rmax][j] = arr[idx];
idx++;
}
rmax--;
//right wall
for (int i = rmax; i >= rmin; i--) {
mat[i][cmax] = arr[idx];
idx++;
}
cmax--;
//top wall
for (int j = cmax; j >= cmin; j--) {
mat[rmin][j] = arr[idx];
idx++;
}
}
public static void rotate(int arr[], int r) {
r = r % arr.length;
if (r < 0) {
r = r + arr.length;
}
reverse(arr, arr.length - r, arr.length - 1);
reverse(arr, 0, arr.length - r - 1);
reverse(arr, 0, arr.length - 1);
}
public static void reverse(int arr[], int si, int ei) {
while (si < ei) {
int temp = arr[si];
arr[si] = arr[ei];
arr[ei] = temp;
si++;
ei--;
}
}
public static void display(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();
}
}
}