Show problems as
Classic problem #1861MediumArrayTwo PointersMatrix

Rotating the Box

Real-world version: Turned Bearing Crate
Tracked in this browser only
Read Rotating the Box on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A crate is packed into cells, given as boxGrid with one one-character string per cell:

  • "#" is a loose ball bearing,
  • "*" is a strut fixed to the crate,
  • "." is an empty cell.

A handler tips the crate a quarter turn clockwise, so the column that was leftmost ends up as the top row. The struts stay bolted where they are, and once the crate is at rest every bearing has slid straight down as far as it can go, stopping on the crate floor, on a strut, or on another bearing that has already come to rest.

Return the cells of the crate after the turn and the settling. If boxGrid has m rows and n columns, the answer has n rows and m columns.

Examples

Example 1

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

The single row becomes a single column, top to bottom in the order the row ran. The two bearings left of the strut come to rest on top of it, and the bearing on the far side of the strut lands on the crate floor.

Example 2

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

The turn puts the old first column across the top row, so the strut lands at the top left. Both bearings end up on the bottom row of the turned crate.

Example 3

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

The bearing that shared a row with the strut settles into the bottom right area, and the two bearings from the first row of the crate finish in the last two rows of the last column.

Constraints

  • m == boxGrid.length
  • n == boxGrid[r].length
  • 1 <= m, n <= 500
  • boxGrid[r][c] is "#", "*" or ".".

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def rotate_the_box(boxGrid: list[list[str]]) -> list[list[str]]:
Java
public char[][] rotateTheBox(char[][] boxGrid)