1972. Rotating The Box¶
Difficulty: Medium
LeetCode Problem View on GitHub
1972. Rotating the Box
Medium
You are given an m x n matrix of characters box representing a side-view of a box. Each cell of the box is one of the following:
- A stone
'#' - A stationary obstacle
'*' - Empty
'.'
The box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions.
It is guaranteed that each stone in box rests on an obstacle, another stone, or the bottom of the box.
Return an n x m matrix representing the box after the rotation described above.
Example 1:

Input: box = [["#",".","#"]] Output: [["."], ["#"], ["#"]]
Example 2:

Input: box = [["#",".","*","."], ["#","#","*","."]] Output: [["#","."], ["#","#"], ["*","*"], [".","."]]
Example 3:

Input: box = [["#","#","*",".","*","."], ["#","#","#","*",".","."], ["#","#","#",".","#","."]] Output: [[".","#","#"], [".","#","#"], ["#","#","*"], ["#","*","."], ["#",".","*"], ["#",".","."]]
Constraints:
m == box.lengthn == box[i].length1 <= m, n <= 500box[i][j]is either'#','*', or'.'.
Solution¶
class Solution {
public char[][] rotateTheBox(char[][] box) {
int r = box.length, c = box[0].length;
char[][] res = new char[c][r];
for(int i = 0; i < r; i++) {
int last = c - 1;
for(int j = c - 1; j >= 0; j--) {
if(box[i][j] == '*') {
last = j - 1;
res[j][i] = '*';
}
else if(box[i][j] == '#') {
res[j][i] = '.';
res[last--][i] = '#';
}
else res[j][i] = '.';
}
}
int left = 0, right = r - 1;
while(left < right) {
for(int i = 0; i < c; i++) {
char temp = res[i][left];
res[i][left] = res[i][right];
res[i][right] = temp;
}
left++;
right--;
}
return res;
}
}
Complexity Analysis¶
- Time Complexity:
O(?) - Space Complexity:
O(?)
Approach¶
Detailed explanation of the approach will be added here