-
Notifications
You must be signed in to change notification settings - Fork 0
/
1861.Rotating the Box
69 lines (62 loc) · 2.27 KB
/
1861.Rotating the Box
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
import java.util.Stack;
class Solution {
static class pair {
int f;
int s;
pair(int f, int s) {
this.f = f;
this.s = s;
}
}
public char[][] rotateTheBox(char[][] box) {
int n = box.length; // number of rows
int m = box[0].length; // number of columns
// Create a new 2D array for the rotated box
char[][] reversed = new char[m][n];
// Initialize reversed array with '.'
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
reversed[i][j] = '.';
}
}
// Process each row of the original box
for (int i = 0; i < n; i++) {
Stack<Character> st = new Stack<>();
// Traverse the row from bottom to top to simulate gravity
for (int j = 0; j < m; j++) {
if (box[i][j] == '#') {
st.push('#');
// System.out.print(i+" "+j);
// Push '#' onto the stack
} else if (box[i][j] == '*') {
reversed[j][i] = '*'; // Place '*' in the rotated posit
int fi = j-1;
while (!st.isEmpty() && fi!=-1) {
char a =st.pop();
reversed[fi][i] = '#'; // Place '#' in the rotated
fi--;
}
}
}
System.out.print(st.size());
int si=box[0].length-1;
// if(!st.isEmpty()){ System.out.print(st.size());}
while (!st.isEmpty() && si!=-1) {
char a=st.pop();
// System.out.print(st.size());
// System.out.print(si+" "+i);
reversed[si][i] = '#'; // Place '#' in the rotated
si--;
}
}
int mid=reversed[0].length/2;
for(int i=0;i<reversed.length;i++){
for(int j=0;j<mid;j++){
char temp=reversed[i][j];
reversed[i][j]=reversed[i][reversed[0].length-1-j];
reversed[i][reversed[0].length-1-j]=temp;
}
}
return reversed; // Return the rotated box
}
}