Two Pointers | Solution for LeectCode#1861
\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem involves rotating a box represented by a 2D array and then simulating
![image.png](https://assets.leetcode.com/users/images/22847af7-3b53-4b75-b8b0-ff6946cb1cd8_1732325116.9412.png)\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem involves rotating a box represented by a 2D array and then simulating gravity to make the stones fall to the bottom. The key insight is to handle the rotation first and then deal with the gravity simulation.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Rotate the box:\n\t- Create a new 2D array with dimensions swapped (n x m instead of m x n).\n\t- Fill the new array by rotating the original box 90 degrees clockwise.\n2. Simulate gravity:\n\t- For each column in the rotated box, start from the bottom.\n\t- Use two pointers: one for the current bottom position (b) and one for the current top position (t).\n\t- Move stones down to fill empty spaces, stopping at obstacles.\n\t\n# Complexity\n- Time complexity: O(m * n)\nWhere m is the number of rows and n is the number of columns in the original box.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n * m) \n We create a new 2D array (rotatedBox) of size n x m to store the rotated and gravity-applied result.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n    public char[][] rotateTheBox(char[][] box) {\n        int m=box.length;\n        int n=box[0].length;\n        char[][] rotatedBox=new char[n][m];\n\n        // Rotating the box by 90 degree\n        for(int i=0; i<n; i++){\n            for(int j=0; j<m; j++){\n                rotatedBox[i][j] = box[m - 1 - j][i];\n            }\n        }\n\n        // Iterating from bottom to top\n        for(int j=0; j<m; j++){//m:Column\n            int b=n-1, t=n-1;\n            while(b>=t && t>=0){//n:Row\n                if(rotatedBox[b][j]==\'#\'){\n                    b--;\n                }\n                else if(rotatedBox[b][j]==\'.\' && rotatedBox[t][j]==\'#\'){\n                    rotatedBox[b][j] = rotatedBox[t][j];\n                    rotatedBox[t][j]=\'.\';\n                    b--;\n                }\n                else if(rotatedBox[t][j]==\'*\'){                    \n                    b=t-1;\n                }\n                t--;\n            }\n        }\n\n\n        return rotatedBox;\n    }\n}\n```
['Java']