Rotating the Box

medium matrix two pointers

Problem

Given an m×n box of '#' (stones), '*' (obstacles), '.' (empty), rotate 90° clockwise and let gravity settle the stones to the right (originally bottom).

Inputbox = [["#",".","#"]]
Output[["."],["#"],["#"]]
After gravity: '..##' becomes '..##' before rotation; rotated → columns of stones at bottom.

def rotate_the_box(box):
    m, n = len(box), len(box[0])
    for row in box:
        write = n - 1
        for c in range(n - 1, -1, -1):
            if row[c] == '*':
                write = c - 1
            elif row[c] == '#':
                row[write], row[c] = '#', ('.' if write != c else '#')
                write -= 1
    # rotate 90 cw
    return [[box[m - 1 - r][c] for r in range(m)] for c in range(n)]
function rotateTheBox(box) {
  const m = box.length, n = box[0].length;
  for (const row of box) {
    let write = n - 1;
    for (let c = n - 1; c >= 0; c--) {
      if (row[c] === '*') write = c - 1;
      else if (row[c] === '#') {
        row[write] = '#';
        if (write !== c) row[c] = '.';
        write--;
      }
    }
  }
  const out = Array.from({length: n}, () => new Array(m));
  for (let r = 0; r < m; r++)
    for (let c = 0; c < n; c++)
      out[c][m - 1 - r] = box[r][c];
  return out;
}
class Solution {
    public char[][] rotateTheBox(char[][] box) {
        int m = box.length, n = box[0].length;
        for (char[] row : box) {
            int write = n - 1;
            for (int c = n - 1; c >= 0; c--) {
                if (row[c] == '*') write = c - 1;
                else if (row[c] == '#') {
                    row[write] = '#';
                    if (write != c) row[c] = '.';
                    write--;
                }
            }
        }
        char[][] out = new char[n][m];
        for (int r = 0; r < m; r++)
            for (int c = 0; c < n; c++)
                out[c][m - 1 - r] = box[r][c];
        return out;
    }
}
vector<vector<char>> rotateTheBox(vector<vector<char>>& box) {
    int m = box.size(), n = box[0].size();
    for (auto& row : box) {
        int write = n - 1;
        for (int c = n - 1; c >= 0; c--) {
            if (row[c] == '*') write = c - 1;
            else if (row[c] == '#') { row[write] = '#'; if (write != c) row[c] = '.'; write--; }
        }
    }
    vector<vector<char>> out(n, vector<char>(m));
    for (int r = 0; r < m; r++)
        for (int c = 0; c < n; c++)
            out[c][m - 1 - r] = box[r][c];
    return out;
}
Time: O(m·n) Space: O(m·n)