← All problems

1861. Rotating the Box

MediumOpen on LeetCodeProblem statement

Problem Statement

1861. 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:

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:

Java

Source file
class Solution {
    public char[][] rotateTheBox(char[][] box) {
        // 90 deg frozen flip... j' = lastCell - i; i' = j
        int m = box.length, n = box[0].length;
        char[][] box90 = new char[n][m]; // rows & cols count reversed
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++)
                box90[i][j] = box[m - 1 - j][i];
        // turn on gravity... free fall along y axis
        for (int i = n - 1; i >= 0; i--) {
            for (int j = 0; j < m; j++)
                if (box90[i][j] == '#') {
                    int y = i + 1;
                    while (y < n && box90[y][j] == '.')
                        y++;
                    box90[y - 1][j] = '#';
                    if (y != i + 1)
                        box90[i][j] = '.';
                }
        }
        return box90;
    }
}