Bootstrap

leetcode - 1861. Rotating the Box

Description

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 ‘#’
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 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:

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

Solution

Simulation

Brute force simulation. First rotate the box, when rotating 9 0 ∘ 90^\circ 90, the new x would be the old y. And the new y would be m - old x.

Iterate all the element in the box, and generate the rotated box. Time complexity for this step is o ( m ∗ n ) o(m*n) o(mn), space complexity is also o ( m ∗ n ) o(m*n) o(mn)

Then to handle the falling items, start from the bottom. If the current position is empty, then find the nearest item above. If it’s a stone, then move it. Keep searching above until we hit the top. Time complexity for this step is o ( m ∗ n ) o(m*n) o(mn).

Overall time complexity: o ( m ∗ n ) o(m*n) o(mn)
Space complexity: o ( m ∗ n ) o(m*n) o(mn)

2 pointers

Solved after help
We could fall first, and then rotate. To fall, since we would rotate 9 0 ∘ 90^\circ 90, so the right side would be the bottom. Thus we could move the stones from left to right.
The moving is actually a 2 pointers process. We have a pointer to point to the boundary of stones, and another pointer points to all the unsorted items. If we have an obstacle, then move the boundary at its left.

Time complexity for this step: o ( m ∗ n ) o(m*n) o(mn)
Space complexity: o ( 1 ) o(1) o(1)

After falling all the stones, we rotate the array. Here I used the rotation trick from the solution. To better understand we could also use the rotation in the previous solution.

Code

Simulation

class Solution:
    def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:
        def find_cloest_non_empty_block(matrix: list, x: int, y: int):
            for above_x in range(x - 1, -1, -1):
                if matrix[above_x][y] != '.':
                    return above_x
            return -1
        # rotate 90
        m, n = len(box), len(box[0])
        rotated_box = [['.'] * m for _ in range(n)]
        for i in range(m):
            for j in range(n):
                if box[i][j] != '.':
                    new_x, new_y = j, m - i - 1
                    rotated_box[new_x][new_y] = box[i][j]
        # fall
        for y in range(m):
            x = n - 1
            while x >= 0:
                if rotated_box[x][y] == '.':
                    # find nearest non-empty block
                    nearest_x = find_cloest_non_empty_block(rotated_box, x, y)
                    if nearest_x != -1 and rotated_box[nearest_x][y] == '#':
                        rotated_box[x][y] = '#'
                        rotated_box[nearest_x][y] = '.'
                x -= 1
        return rotated_box

2 pointers

class Solution:
    def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:
        for row in box:
            last_empty = len(row) - 1
            for j in range(len(row) - 1, -1, -1):
                if row[j] == '*':
                    last_empty = j - 1
                elif row[j] == '#':
                    row[last_empty], row[j] = row[j], row[last_empty]
                    last_empty -= 1
        return list(zip(*box[::-1]))
;