33. Rotating the Box

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: [[".","#","#"],
         [".","#","#"],
         ["#","#","*"],
         ["#","*","."],
         ["#",".","*"],
         ["#",".","."]]

Solution:

Approach: Rotate by 90 degree(transpose and swap) Check for falling stones

class Solution
{
public:
    vector<vector<char>> rotateTheBox(vector<vector<char>> &box)
    {

        int n = box.size();
        int m = box[0].size();

        vector<vector<char>> res(m, vector<char>(n));

        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                res[i][j] = box[j][i];
            }
        }
        
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n / 2; j++)
            {
                int temp = res[i][j];
                res[i][j] = res[i][n - 1 - j];
                res[i][n - 1 - j] = temp;
            }
        }

        for (int i = 0; i < n; i++)
        {

            int j = 0;
            
            int prev = 0;
            while (j < m)
            {
                
                int stone = 0;
                while (j < m && res[j][i] != '*')
                {

                    if (res[j][i] == '#')
                    {
                        stone++;
                    }

                    j++;
                }

                for (int k = j - 1; k >= prev; k--)
                {
                    if (stone)
                    {
                        res[k][i] = '#';
                        stone--;
                    }
                    else
                    {
                        res[k][i] = '.';
                    }
                }

                j++;
                prev = j;
            }
        }

        return res;
    }
};

Time Complexity: O(n * m)

Last updated