Leetcode Problem:
Summary
- Given an m x n matrix of characters boxGrid representing a side-view of a box, rotate the box 90 degrees clockwise and return the resulting matrix.
Approach
- The approach used is to first transpose the boxGrid and then reverse each row of the transposed matrix
- This is because the problem requires us to rotate the box 90 degrees clockwise, which can be achieved by first flipping the box horizontally and then flipping it vertically.
Complexity
- O(m*n) where m is the number of rows and n is the number of columns in the boxGrid.
Explanation
- The solution code first creates a new 2D vector rotateBox to store the resulting matrix
- It then iterates over each row in the boxGrid and performs the following operations: 1
- It starts from the rightmost column and moves towards the left
- If the current cell is a stone (#), it moves the stone to the bottom right corner of the row and marks the stone as empty (.) if it's not the last stone in the row
- 2
- If the current cell is an obstacle (*), it moves the obstacle to the left of the stone
- 3
- If the current cell is empty (.), it simply moves to the next cell
- After processing each row, the code transposes the boxGrid and reverses each row to achieve the rotation
- Finally, it returns the resulting matrix.
Solution Code:
class Solution {
public:
vector> rotateTheBox(vector>& box) {
vector> rotateBox;
for(int i = 0 ; i< box.size(); i++){
int r = box[0].size() - 1;
int l = r;
while(l >= 0){
if(box[i][l] == '#'){
box[i][r] = box[i][l];
if(l != r){
box[i][l] = '.';
}
r--;
} else if(box[i][l] == '*'){
r = l - 1;
}
l--;
}
}
int R = box.size();
int C = box[0].size();
for(int j=0; j < C; j++){
rotateBox.push_back(vector());
for(int i = 0; i < R; i++){
rotateBox[j].push_back(box[R-i-1][j]);
}
}
return rotateBox;
}
};
class Solution {
public:
vector> rotateTheBox(vector>& box) {
vector> rotateBox;
for(int i = 0 ; i< box.size(); i++){
int r = box[0].size() - 1;
int l = r;
while(l >= 0){
if(box[i][l] == '#'){
box[i][r] = box[i][l];
if(l != r){
box[i][l] = '.';
}
r--;
} else if(box[i][l] == '*'){
r = l - 1;
}
l--;
}
}
int R = box.size();
int C = box[0].size();
for(int j=0; j < C; j++){
rotateBox.push_back(vector());
for(int i = 0; i < R; i++){
rotateBox[j].push_back(box[R-i-1][j]);
}
}
return rotateBox;
}
};
'알고리즘' 카테고리의 다른 글
Sliding Puzzle (0) | 2025.02.22 |
---|---|
Maximum Matrix Sum (0) | 2025.02.22 |
Flip Columns For Maximum Number of Equal Rows (0) | 2025.02.22 |
Count Unguarded Cells in the Grid (0) | 2025.02.22 |
Take K of Each Character From Left and Right (0) | 2025.02.22 |