Rotate the Box 🧩 | Matrix Rotation & Gravity Simulation 💡
Intuition \uD83D\uDCA1\n\nTo solve the problem of rotating the box and simulating the effects of gravity on stones (#), the solution involves:\n\n1. Matrix Rota
# Intuition \uD83D\uDCA1\n\nTo solve the problem of rotating the box and simulating the effects of gravity on stones (`#`), the solution involves:\n\n1. **Matrix Rotation**:  \n   The $$ m \\times n $$ matrix is rotated 90 degrees clockwise. Rows in the original matrix become columns in the result.\n\n2. **Gravity Simulation**:  \n   Stones fall to the lowest available positions in their column, stopping on obstacles (`*`) or the bottom.\n\n---\n\n# Approach \uD83D\uDEE0\uFE0F\n\n### 1. **Result Matrix Initialization**  \n   - The result matrix is initialized with dimensions $$ n \\times m $$, as the rows and columns are swapped after rotation. All cells start as empty (`.`).\n\n### 2. **Processing Rows with Gravity**  \n   - For each row in the original matrix:\n     - Traverse backward to simulate gravity, using a pointer to track the lowest position a stone can occupy.\n     - Stones (`#`) move to the lowest valid position, while obstacles (`*`) remain fixed and reset the pointer.\n\n### 3. **Final Matrix Construction**  \n   - Populate the result matrix column-by-column based on the rotated and gravity-adjusted state of the original matrix.\n\n---\n\n# Complexity \u23F3\n\n- **Time Complexity**:  \n  $$ O(m \\cdot n) $$, where $$ m $$ is the number of rows and $$ n $$ is the number of columns. Each cell is processed once.\n\n- **Space Complexity**:  \n  $$ O(m \\cdot n) $$ for the result matrix.\n\n---\n![c1ee5054-dd07-4caa-a7df-e21647cfae9e_1709942227.5165014.png](https://assets.leetcode.com/users/images/2e634cb4-2894-428e-8ed8-c637bc23e681_1732334821.8246338.png)\n\n\n# Code \uD83D\uDCBB  \n\n```cpp []\nclass Solution {\npublic:\n    vector<vector<char>> rotateTheBox(vector<vector<char>>& box) {\n        int rows = box.size(), cols = box[0].size();\n        vector<vector<char>> result(cols, vector<char>(rows, \'.\')); // Initialize result matrix\n        \n        // Process each row of the box\n        for (int i = 0; i < rows; i++) {\n            int emptyPosition = cols - 1; // Track the lowest position for stones\n            for (int j = cols - 1; j >= 0; j--) {\n                if (box[i][j] == \'*\') {\n                    // Obstacle: place it in the result and reset the empty position\n                    result[j][rows - i - 1] = \'*\';\n                    emptyPosition = j - 1;\n                } else if (box[i][j] == \'#\') {\n                    // Stone: move it to the lowest available position\n                    result[emptyPosition][rows - i - 1] = \'#\';\n                    emptyPosition--;\n                }\n            }\n        }\n        \n        return result;\n    }\n};\n```\n``` java []\nclass Solution {\n    public char[][] rotateTheBox(char[][] box) {\n        int rows = box.length, cols = box[0].length;\n        char[][] result = new char[cols][rows]; // Initialize result matrix\n        \n        // Fill the result matrix with empty spaces\n        for (char[] row : result) {\n            java.util.Arrays.fill(row, \'.\');\n        }\n\n        // Process each row of the box\n        for (int i = 0; i < rows; i++) {\n            int emptyPosition = cols - 1; // Track the lowest position for stones\n            for (int j = cols - 1; j >= 0; j--) {\n                if (box[i][j] == \'*\') {\n                    // Obstacle: place it in the result and reset the empty position\n                    result[j][rows - i - 1] = \'*\';\n                    emptyPosition = j - 1;\n                } else if (box[i][j] == \'#\') {\n                    // Stone: move it to the lowest available position\n                    result[emptyPosition][rows - i - 1] = \'#\';\n                    emptyPosition--;\n                }\n            }\n        }\n        \n        return result;\n    }\n}\n\n```\n```python []\nclass Solution:\n    def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:\n        rows, cols = len(box), len(box[0])\n        result = [[\'.\' for _ in range(rows)] for _ in range(cols)]  # Initialize result matrix\n        \n        # Process each row of the box\n        for i in range(rows):\n            empty_position = cols - 1  # Track the lowest position for stones\n            for j in range(cols - 1, -1, -1):\n                if box[i][j] == \'*\':\n                    # Obstacle: place it in the result and reset the empty position\n                    result[j][rows - i - 1] = \'*\'\n                    empty_position = j - 1\n                elif box[i][j] == \'#\':\n                    # Stone: move it to the lowest available position\n                    result[empty_position][rows - i - 1] = \'#\'\n                    empty_position -= 1\n\n        return result\n\n```\n```javascript []\n/**\n * @param {character[][]} box\n * @return {character[][]}\n */\nvar rotateTheBox = function(box) {\n    const rows = box.length, cols = box[0].length;\n    const result = Array.from({ length: cols }, () => Array(rows).fill(\'.\')); // Initialize result matrix\n\n    // Process each row of the box\n    for (let i = 0; i < rows; i++) {\n        let emptyPosition = cols - 1; // Track the lowest position for stones\n        for (let j = cols - 1; j >= 0; j--) {\n            if (box[i][j] === \'*\') {\n                // Obstacle: place it in the result and reset the empty position\n                result[j][rows - i - 1] = \'*\';\n                emptyPosition = j - 1;\n            } else if (box[i][j] === \'#\') {\n                // Stone: move it to the lowest available position\n                result[emptyPosition][rows - i - 1] = \'#\';\n                emptyPosition--;\n            }\n        }\n    }\n\n    return result;\n};\n\n```\n\n---\n\n# Explanation \uD83D\uDCD8  \n\n### Example 1  \n```plaintext\nInput: box = \n[\n  [\'#\', \'.\', \'#\'],\n  [\'#\', \'#\', \'*\'],\n  [\'#\', \'.\', \'.\']\n]\nOutput: \n[\n  [\'.\', \'#\', \'#\'],\n  [\'#\', \'#\', \'*\'],\n  [\'#\', \'.\', \'.\']\n]\n\nExplanation: \n- After rotating the box, gravity causes stones to fall to the lowest positions in their respective columns.\n```\n\n### Example 2  \n```plaintext\nInput: box = \n[\n  [\'#\', \'.\', \'*\', \'.\'],\n  [\'#\', \'#\', \'*\', \'.\'],\n  [\'#\', \'.\', \'.\', \'*\']\n]\nOutput: \n[\n  [\'.\', \'.\', \'*\'],\n  [\'.\', \'#\', \'*\'],\n  [\'#\', \'#\', \'*\'],\n  [\'#\', \'.\', \'.\']\n]\n```\n\n---\n\n# Takeaway \uD83D\uDE80\n\nThis solution elegantly handles the dual challenges of matrix rotation and simulating gravity by decoupling the two steps. This results in clean, efficient code with minimal overhead. If this approach resonates with you, **upvote and share**! \uD83D\uDE0A\n\n![1HBC0324_COV.jpg](https://assets.leetcode.com/users/images/13fdbf96-17aa-44e9-b6b3-d39263e517e5_1732334788.150529.jpeg)
['Array', 'Two Pointers', 'Matrix', 'C++', 'Java', 'Python3', 'JavaScript']