2024-11-23 Daily Challenge

Today I have done leetcode's November LeetCoding Challenge with cpp.

November LeetCoding Challenge 23

Description

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

 

Constraints:

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

Solution


template<typename T>
std::ostream& operator<<(std::ostream &out, const std::vector<T> &v) {
  if(v.size() == 0) {
    out << "[]" << std::endl;
    return out;
  }
  out << '[' << v[0];
  for(int i = 1; i < v.size(); ++i) {
    out << ", " << v[i];
  }
  out << ']';
  return out;
}
class Solution {
  vector<vector<char>> rotate(vector<vector<char>>& matrix) {
    int rows = matrix.size();
    int cols = matrix.front().size();
    vector<vector<char>> answer;
    for(int i = 0; i < cols; ++i) {
      vector<char> row(rows);
      for(int j = 0; j < rows; ++j) {
        row[j] = matrix[rows - 1 - j][i];
      }
      answer.emplace_back(row);
    }
    return move(answer);
  }
public:
  vector<vector<char>> rotateTheBox(vector<vector<char>>& box) {
    int rows = box.size();
    int cols = box.front().size();
    for(int row = 0; row < rows; ++row) {
      int stones = 0;
      for(int col = 0; col < cols; ++col) {
        if(box[row][col] == '#') {
          stones += 1;
          box[row][col] = '.';
        } else if (box[row][col] == '*') {
          while(stones) {
            box[row][col - stones] = '#';
            stones -= 1;
          }
        }
        while(col == cols - 1 && stones) {
          box[row][cols - stones] = '#';
          stones -= 1;
        }
      }
    }
    return rotate(box);
  }
};