You are given an m x n matrix of characters boxGrid representing a side-view of a box. Each cell of the box is one of the following:
'#''*''.'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 boxGrid 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: boxGrid = [
["#",".","*","."],
["#","#","*","."]
]
Output: [
["#","."],
["#","#"],
["*","*"],
[".","."]
]Example 2:
Input: boxGrid = [
["#","#","*",".","*","."],
["#","#","#","*",".","."],
["#","#","#",".","#","."]
]
Output: [
[".","#","#"],
[".","#","#"],
["#","#","*"],
["#","*","."],
["#",".","*"],
["#",".","."]
]Constraints:
m == boxGrid.lengthn == boxGrid[i].length1 <= m, n <= 500boxGrid[i][j] is either '#', '*', or '.'.class Solution:
def rotateTheBox(self, boxGrid: List[List[str]]) -> List[List[str]]:
ROWS, COLS = len(boxGrid), len(boxGrid[0])
for r in range(ROWS - 1, -1, -1):
for c1 in range(COLS - 1, -1, -1):
if boxGrid[r][c1] == '#':
c2 = c1 + 1
while c2 < COLS and boxGrid[r][c2] == '.':
c2 += 1
boxGrid[r][c1] = '.'
boxGrid[r][c2 - 1] = '#'
res = []
for c in range(COLS):
col = []
for r in range(ROWS - 1, -1, -1):
col.append(boxGrid[r][c])
res.append(col)
return resWhere is the number of rows and is the number of columns.
class Solution:
def rotateTheBox(self, boxGrid: List[List[str]]) -> List[List[str]]:
ROWS, COLS = len(boxGrid), len(boxGrid[0])
for r in range(ROWS):
i = COLS - 1
for c in reversed(range(COLS)):
if boxGrid[r][c] == "#":
boxGrid[r][c], boxGrid[r][i] = boxGrid[r][i], boxGrid[r][c]
i -= 1
elif boxGrid[r][c] == "*":
i = c - 1
res = []
for c in range(COLS):
col = [] # this is a row after rotation
for r in reversed(range(ROWS)):
col.append(boxGrid[r][c])
res.append(col)
return resWhere is the number of rows and is the number of columns.
class Solution:
def rotateTheBox(self, boxGrid: List[List[str]]) -> List[List[str]]:
ROWS, COLS = len(boxGrid), len(boxGrid[0])
res = [["."] * ROWS for _ in range(COLS)]
for r in range(ROWS):
i = COLS - 1
for c in reversed(range(COLS)):
if boxGrid[r][c] == "#":
res[i][ROWS - r - 1] = "#"
i -= 1
elif boxGrid[r][c] == "*":
res[c][ROWS - r - 1] = "*"
i = c - 1
return resWhere is the number of rows and is the number of columns.