1861. Rotating the Box #867
-
Topics: You are given an
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 Return an Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to follow a few distinct steps:
Approach:
Step-by-step explanation:
Let's implement this solution in PHP: 1861. Rotating the Box <?php
function rotateTheBox($box) {
$m = count($box); // Number of rows
$n = count($box[0]); // Number of columns
// Step 1: Apply gravity to each row
for ($i = 0; $i < $m; $i++) {
$emptySlot = $n - 1; // Index of the empty slot in the current row
for ($j = $n - 1; $j >= 0; $j--) {
if ($box[$i][$j] === '#') {
// Move stone to the lowest possible position
$box[$i][$j] = '.';
$box[$i][$emptySlot] = '#';
$emptySlot--;
} elseif ($box[$i][$j] === '*') {
// Reset emptySlot to just above the obstacle
$emptySlot = $j - 1;
}
}
}
// Step 2: Rotate the box 90 degrees clockwise
$rotatedBox = [];
for ($j = 0; $j < $n; $j++) {
$newRow = [];
for ($i = $m - 1; $i >= 0; $i--) {
$newRow[] = $box[$i][$j];
}
$rotatedBox[] = $newRow;
}
return $rotatedBox;
}
// Example Usage
$box = [
["#", ".", "#"],
];
print_r(rotateTheBox($box));
$box = [
["#", ".", "*", "."],
["#", "#", "*", "."],
];
print_r(rotateTheBox($box));
$box = [
["#", "#", "*", ".", "*", "."],
["#", "#", "#", "*", ".", "."],
["#", "#", "#", ".", "#", "."],
];
print_r(rotateTheBox($box));
?> Explanation:
Example OutputInput:$box = [
["#", ".", "#"],
]; Output:[
[".",],
["#",],
["#",],
] Input:$box = [
["#", ".", "*", "."],
["#", "#", "*", "."],
]; Output:[
["#", "."],
["#", "#"],
["*", "*"],
[".", "."],
] Time Complexity
Total: O(m x n). Space Complexity
This solution is efficient and adheres to the constraints of the problem. |
Beta Was this translation helpful? Give feedback.
We need to follow a few distinct steps:
Rotate the box: We first rotate the matrix 90 degrees clockwise. The rotated matrix will have
n
rows andm
columns, wheren
is the number of columns in the original box, andm
is the number of rows.Gravity effect: After rotating, we need to simulate the effect of gravity. This means that all stones (
'#'
) should "fall" to the bottom of their new column, stopping only when they encounter an obstacle ('*'
) or another stone ('#'
).Approach:
Rotation: After the rotation, the element at position
[i][j]
in the original matrix will be placed at position[j][m-1-i]
in the rotated matrix.Gravity simulation: We need to process each column from bott…