Talentd
FleetCode

1861. Rotating the Box

Medium82.4% acceptance10 companies

You are given an m x n matrix of characters boxGrid 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 boxGrid 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: boxGrid = [["#",".","#"]]
Output: [["."],
         ["#"],
         ["#"]]

Example 2:

Input: boxGrid = [["#",".","*","."],
              ["#","#","*","."]]
Output: [["#","."],
         ["#","#"],
         ["*","*"],
         [".","."]]

Example 3:

Input: boxGrid = [["#","#","*",".","*","."],
              ["#","#","#","*",".","."],
              ["#","#","#",".","#","."]]
Output: [[".","#","#"],
         [".","#","#"],
         ["#","#","*"],
         ["#","*","."],
         ["#",".","*"],
         ["#",".","."]]

Constraints:

  • m == boxGrid.length
  • n == boxGrid[i].length
  • 1 <= m, n <= 500
  • boxGrid[i][j] is either '#', '*', or '.'.

Hints open one at a time

Hint 1
Rotate the box using the relation rotatedBox[i][j] = box[m - 1 - j][i].
Hint 2
Start iterating from the bottom of the box and for each empty cell check if there is any stone above it with no obstacles between them.
15:14
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def rotateTheBox(self, boxGrid: List[List[str]]) -> List[List[str]]:
3
Starter codePython 3Spaces: 4
Examples
Input
[["#",".","#"]]
Input
[["#",".","*","."],["#","#","*","."]]
Input
[["#","#","*",".","*","."],["#","#","#","*",".","."],["#","#","#",".","#","."]]
Your code is saved on this device.Solution