Leetcode 1861: Rotating the Box

grid47
grid47
Exploring patterns and algorithms
May 4, 2024 7 min read

You are given an m x n matrix of characters box, where each cell is a stone (#), a stationary obstacle (*), or an empty space (.). After rotating the box 90 degrees clockwise, gravity will cause stones to fall down until they land on an obstacle, another stone, or the bottom. Return the updated matrix after the stones have fallen.
Problem
Approach
Steps
Complexity
Input: The input is an m x n matrix of characters where each cell can either be a stone (`#`), a stationary obstacle (`*`), or an empty space (`.`).
Example: box = [[# , ., *], [#, *, #]]
Constraints:
• 1 <= m, n <= 500
• Each box[i][j] is either '#', '*', or '.'
Output: The output is the updated matrix representing the box after the stones have fallen due to gravity, while obstacles remain stationary.
Example: Output = [[#, .], [#, #], [*, *], [., .]]
Constraints:
• The output is an m x n matrix of characters, representing the new arrangement after the stones have fallen.
Goal: Simulate the rotation and gravity effect to correctly place the stones.
Steps:
• Step 1: Reverse the rows of the matrix to simulate a 90-degree clockwise rotation.
• Step 2: Iterate over each column, from bottom to top, and move the stones downwards, stopping at obstacles or other stones.
• Step 3: Rebuild the matrix by placing stones at the bottom, obstacles where they are, and empty spaces above the stones.
Goal: The constraints are simple, ensuring that the input matrix is not too large and consists only of the allowed characters.
Steps:
• The matrix dimensions are between 1 and 500 for both rows and columns.
• Each character in the matrix is one of '#', '*', or '.'
Assumptions:
• The matrix is guaranteed to contain at least one row and one column.
• The stones are already placed in a valid position, meaning they will rest on an obstacle, another stone, or the bottom of the box.
Input: Input: [[., ., #]]
Explanation: After rotating the box 90 degrees and applying gravity, the stone falls to the bottom.

Input: Input: [[., *, ., #], [., #, *, #]]
Explanation: The stones fall to the bottom after rotation, and the obstacles remain in place, causing the stones to settle above them.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus