Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1861.html

1861. Rotating the Box

Level

Medium

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:

Image text

Input: box = [["#",".","#"]]
Output: [["."],
         ["#"],
         ["#"]]

Example 2:

Image text

Input: box = [["#",".","*","."],
              ["#","#","*","."]]
Output: [["#","."],
         ["#","#"],
         ["*","*"],
         [".","."]]

Example 3:

Image text

Input: box = [["#","#","*",".","*","."],
              ["#","#","#","*",".","."],
              ["#","#","#",".","#","."]]
Output: [[".","#","#"],
         [".","#","#"],
         ["#","#","*"],
         ["#","*","."],
         ["#",".","*"],
         ["#",".","."]]

Constraints:

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

Solution

First, move the stones to the rightmost positions considering the border of the box and the obstacles. Then rotate box 90 degrees clockwise.

  • class Solution {
        public char[][] rotateTheBox(char[][] box) {
            int m = box.length, n = box[0].length;
            moveToRight(box);
            char[][] rotated = new char[n][m];
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++)
                    rotated[j][m - 1 - i] = box[i][j];
            }
            return rotated;
        }
    
        public void moveToRight(char[][] box) {
            int m = box.length, n = box[0].length;
            for (int i = 0; i < m; i++) {
                int prevObstacle = n;
                int stones = 0;
                for (int j = n - 1; j >= 0; j--) {
                    if (box[i][j] == '*') {
                        int k = prevObstacle - 1;
                        while (k > j && stones > 0) {
                            box[i][k] = '#';
                            k--;
                            stones--;
                        }
                        while (k > j) {
                            box[i][k] = '.';
                            k--;
                        }
                        prevObstacle = j;
                    } else if (box[i][j] == '#')
                        stones++;
                }
                if (stones > 0) {
                    int k = prevObstacle - 1;
                    while (k >= 0 && stones > 0) {
                        box[i][k] = '#';
                        k--;
                        stones--;
                    }
                    while (k >= 0) {
                        box[i][k] = '.';
                        k--;
                    }
                }
            }
        }
    }
    
    ############
    
    class Solution {
        public char[][] rotateTheBox(char[][] box) {
            int m = box.length, n = box[0].length;
            char[][] ans = new char[n][m];
            for (int i = 0; i < m; ++i) {
                for (int j = 0; j < n; ++j) {
                    ans[j][m - i - 1] = box[i][j];
                }
            }
            for (int j = 0; j < m; ++j) {
                Deque<Integer> q = new ArrayDeque<>();
                for (int i = n - 1; i >= 0; --i) {
                    if (ans[i][j] == '*') {
                        q.clear();
                    } else if (ans[i][j] == '.') {
                        q.offer(i);
                    } else if (!q.isEmpty()) {
                        ans[q.pollFirst()][j] = '#';
                        ans[i][j] = '.';
                        q.offer(i);
                    }
                }
            }
            return ans;
        }
    }
    
  • class Solution:
        def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:
            m, n = len(box), len(box[0])
            ans = [[None] * m for _ in range(n)]
            for i in range(m):
                for j in range(n):
                    ans[j][m - i - 1] = box[i][j]
            for j in range(m):
                q = deque()
                for i in range(n - 1, -1, -1):
                    if ans[i][j] == '*':
                        q.clear()
                    elif ans[i][j] == '.':
                        q.append(i)
                    elif q:
                        ans[q.popleft()][j] = '#'
                        ans[i][j] = '.'
                        q.append(i)
            return ans
    
    ############
    
    # 1861. Rotating the Box
    # https://leetcode.com/problems/rotating-the-box/
    
    class Solution:
        def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:
            rows, cols = len(box), len(box[0])
            box = [[box[j][i] for j in range(rows)][::-1] for i in range(cols-1,-1,-1)][::-1]
            rows, cols = cols, rows
            
            for j in range(cols):
                canDrop = False
                available = deque()
                prior = deque()
                for i in reversed(range(rows)):
                    if box[i][j] == ".":
                        canDrop = True
                    elif box[i][j] == "*":
                        canDrop = False
                        available.clear()
                        prior.clear()
                    
                    if canDrop:
                        if box[i][j] == ".":
                            available.append(i)
                    
                        elif box[i][j] == "#":
                            if available or prior:
                                if available and prior:
                                    ii = available.popleft() if available[0] > prior[0] else prior.popleft()
                                else:
                                    ii = available.popleft() if available else prior.popleft()
                                        
                                box[ii][j] = '#'
                                box[i][j] = '.'
                                prior.append(i)
            
            return box
            
    
    
  • class Solution {
    public:
        vector<vector<char>> rotateTheBox(vector<vector<char>>& box) {
            int m = box.size(), n = box[0].size();
            vector<vector<char>> ans(n, vector<char>(m));
            for (int i = 0; i < m; ++i) {
                for (int j = 0; j < n; ++j) {
                    ans[j][m - i - 1] = box[i][j];
                }
            }
            for (int j = 0; j < m; ++j) {
                queue<int> q;
                for (int i = n - 1; ~i; --i) {
                    if (ans[i][j] == '*') {
                        queue<int> t;
                        swap(t, q);
                    } else if (ans[i][j] == '.') {
                        q.push(i);
                    } else if (!q.empty()) {
                        ans[q.front()][j] = '#';
                        q.pop();
                        ans[i][j] = '.';
                        q.push(i);
                    }
                }
            }
            return ans;
        }
    };
    
  • func rotateTheBox(box [][]byte) [][]byte {
    	m, n := len(box), len(box[0])
    	ans := make([][]byte, n)
    	for i := range ans {
    		ans[i] = make([]byte, m)
    	}
    	for i := 0; i < m; i++ {
    		for j := 0; j < n; j++ {
    			ans[j][m-i-1] = box[i][j]
    		}
    	}
    	for j := 0; j < m; j++ {
    		q := []int{}
    		for i := n - 1; i >= 0; i-- {
    			if ans[i][j] == '*' {
    				q = []int{}
    			} else if ans[i][j] == '.' {
    				q = append(q, i)
    			} else if len(q) > 0 {
    				ans[q[0]][j] = '#'
    				q = q[1:]
    				ans[i][j] = '.'
    				q = append(q, i)
    			}
    		}
    	}
    	return ans
    }
    

All Problems

All Solutions