# Solution For Rotating The Box

Problem statement:
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 ‘#’ character
• A stationary obstacle ‘*’ character
• Empty ‘.’ character

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 of the stones does not allow a stone to move left or right.

Example:

Input: box = [[“#”,”.”,”#”]] Output: [[“.”],
[“#”],
[“#”]]

Solution:
1. Iterate through each row of the input box.
2. For each row, iterate through each column from right to left.
3. If a stone ‘#’ character is found, check if there is space below it in the current column.
4. If there is empty ‘.’, move the stone down to the empty space and set the original location to empty.
5. If there is an obstacle ‘*’ or another stone ‘#’, check if there is empty space to the left of the obstacle/stone.
6. If there is empty space to the left, move the stone to the empty space and set the original location to empty.
7. If there is no empty space to the left, the stone remains in its original position.
8. After iterating through all rows and columns, return the rotated box.

Sample code:

class Solution:
def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:

``````    # Helper function to move stone to new location and set original location to empty
def move_stone(box: List[List[str]], row: int, col: int, new_row: int, new_col: int) -> None:
box[new_row][new_col] = '#'
box[row][col] = '.'

m, n = len(box), len(box[0])

# Iterate through each row
for i in range(m):
row = box[i]
j = n - 1
k = n - 1

# Iterate through each column from right to left
while j >= 0:

# If stone is found in current column, check if there is space below it
if row[j] == '#':
if j < k:
k = j

if j == 0 or row[j-1] != '#':
empty_row = i

# Move stone down to empty space
while empty_row < m and box[empty_row][j] == '.':
move_stone(box, empty_row, j, empty_row-1, j)
empty_row += 1

# Check if there is obstacle or stone to the left
if j > 0 and (box[empty_row-1][j-1] == '#' or box[empty_row-1][j-1] == '*'):
k = j - 1

# Move stone to empty space to the left
if k < j:
empty_row = i

while empty_row < m and box[empty_row][k] == '.':
move_stone(box, empty_row, j, empty_row, k)
empty_row += 1

k -= 1

j -= 1

# Rotate box 90 degrees clockwise
rotated_box = [[0] * m for _ in range(n)]

for i in range(n):
for j in range(m):
rotated_box[i][j] = box[m-j-1][i]

return rotated_box
``````

Time Complexity:
The code iterates through each element in the input box once, so the time complexity is O(m*n), where m and n are the dimensions of the input box.

Space Complexity:
The code creates a new rotated_box with dimensions nm, so the space complexity is O(mn).

## Step by Step Implementation For Rotating The Box

```class Solution {
public boolean rotateBox(int[][] box) {
// check for empty box
if (box == null || box.length == 0) {
return false;
}
// get the number of rows and columns in the box
int rows = box.length;
int cols = box[0].length;
// create a new box to store the rotated box
int[][] rotatedBox = new int[rows][cols];
// rotate the box
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
rotatedBox[i][j] = box[rows - j - 1][i];
}
}
// check if the new box is equal to the old box
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (rotatedBox[i][j] != box[i][j]) {
return false;
}
}
}
return true;
}
}```
```# Python3 program to rotate a box
# around an arbitrary axis

# A point in 3D space
class Point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z

# A Vector in 3D space
class Vector:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z

# Function to add two vectors
return Vector(self.x + rhs.x, self.y + rhs.y, self.z + rhs.z)

# Function to subtract two vectors
def __sub__(self, rhs):
return Vector(self.x - rhs.x, self.y - rhs.y, self.z - rhs.z)

# Function to calculate cross product of
# two vectors
def cross(self, rhs):
return Vector((self.y * rhs.z) - (self.z * rhs.y),
(self.z * rhs.x) - (self.x * rhs.z),
(self.x * rhs.y) - (self.y * rhs.x))

# Function to calculate dot product of
# two vectors
def dot(self, rhs):
return self.x * rhs.x + self.y * rhs.y + self.z * rhs.z

# Function to calculate magnitude of
# a vector
def magnitude(self):
return (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5

# Function to normalize a vector
def normalize(self):
mag = self.magnitude()
self.x /= mag
self.y /= mag
self.z /= mag

# A Plane in 3D space
class Plane:
def __init__(self, point, normal):
self.point = point
self.normal = normal.normalize()

# Function to calculate distance between
# a point and a plane
def distance(self, point):
# D = ((P-A).B)/|B|
return (self.normal.dot(point - self.point))

# A box aligned with axes
class Box:
def __init__(self, min_x, max_x, min_y, max_y, min_z, max_z):
self.min_x = min_x
self.max_x = max_x
self.min_y = min_y
self.max_y = max_y
self.min_z = min_z
self.max_z = max_z

# Function to rotate a box around an arbitrary axis
def rotate(self, point, axis, theta):

# Rotation matrix for theta around arbitrary axis
# https://en.wikipedia.org/wiki/Rotation_matrix
# cos(theta) 0 -sin(theta)
# 0 1 0
# sin(theta) 0 cos(theta)
c, s = math.cos(theta), math.sin(theta)
R = np.array(((c, 0, s), (0, 1, 0), (-s, 0, c)))

# Translate point to origin
# Make axis unit vector
# Rotate box
# Translate back
O = np.array((0, 0, 0))
O[:] = point[:]
axis = axis / np.linalg.norm(axis)
rotated_points = np.dot(R, self.points - O) + O

# Convert back to box
self.min_x = min(rotated_points[:, 0])
self.max_x = max(rotated_points[:, 0])
self.min_y = min(rotated_points[:, 1])
self.max_y = max(rotated_points[:, 1])
self.min_z = min(rotated_points[:, 2])
self.max_z = max(rotated_points[:, 2])

# Function to check if two boxes intersect
def intersect(self, other):

# Check for intersection in x, y and z
# directions
if (self.max_x >= other.min_x and
self.min_x <= other.max_x and
self.max_y >= other.min_y and
self.min_y <= other.max_y and
self.max_z >= other.min_z and
self.min_z <= other.max_z):
return True
else:
return False

# Driver code
if __name__ == '__main__':

# Points of a box
points = np.array([[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0],
[0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]])

# Create a box
box = Box(0, 1, 0, 1, 0, 1)
box.points = points

# Arbitrary axis and angle
axis = np.array([1, 1, 1])
theta = math.pi / 4

# Rotate the box
box.rotate(np.array([0, 0, 0]), axis, theta)

# Print rotated box
print("Rotated Box:")
print("[(%0.2f, %0.2f, %0.2f), (%0.2f, %0.2f, %0.2f), (%0.2f, %0.2f, %0.2f), (%0.2f, %0.2f, %0.2f)]" %(box.min_x, box.min_y, box.min_z, box.max_x, box.min_y, box.min_z, box.max_x, box.max_y, box.min_z, box.min_x, box.max_y, box.min_z))
print("[(%0.2f, %0.2f, %0.2f), (%0.2f, %0.2f, %0.2f), (%0.2f, %0.2f, %0.2f), (%0.2f, %0.2f, %0.2f)]" %(box.min_x, box.min_y, box.max_z, box.max_x, box.min_y, box.max_z, box.max_x, box.max_y, box.max_z, box.min_x, box.max_y, box.max_z))

# Another box
other = Box(0.5, 1.5, 0.5, 1.5, 0.5, 1.5)

# Check intersection
if (box.intersect(other)):
print("Boxes Intersect")
else:
print("Boxes Do Not Intersect")```
```// Given a rectangular box represented as an array with four elements: [x1, y1, x2, y2], where (x1, y1) are the coordinates of the top left corner, and (x2, y2) are the coordinates of the bottom right corner of the box, find the minimum area of any rectangle formed from the four corners of the box.

// If there is no possible rectangle, return 0.

function rotatingTheBox(box) {
}```
```There are many ways to solve this problem. One approach would be to use a two-dimensional array to represent the box. We would then rotate the box by changing the values in the array.

Another approach would be to use a three-dimensional array to represent the box. We would then rotate the box by changing the values in the array.

Yet another approach would be to use a four-dimensional array to represent the box. We would then rotate the box by changing the values in the array.```
```using System;

public class Solution {

// rotate the box by 90 degrees
public void Rotate(int[][] box)
{

// check for null or empty
if (box == null || box.Length == 0)
{
return;
}

int rows = box.Length;
int cols = box.Length;

// rotate the matrix by 90 degrees

for (int i = 0; i < rows; i++)
{
for (int j = i; j < cols; j++)
{
int temp = box[i][j];
box[i][j] = box[j][i];
box[j][i] = temp;
}
}

// reverse each row
for (int i = 0; i < rows; i++)
{
int start = 0;
int end = cols - 1;

while (start < end)
{
int temp = box[i][start];
box[i][start] = box[i][end];
box[i][end] = temp;
start++;
end--;
}
}
}
}```

Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]