Given a 2D integer matrix matrix and a list of string commands commands, apply each command to transform the matrix and return the final result.
-
"R"
: reverse each row of the matrix (flip horizontally).
-
"C"
: reverse each column of the matrix (flip vertically). This is the same as reversing the order of the rows.
-
"T"
: transpose the matrix (swap rows and columns). A matrix with
rows
rows and
cols
columns becomes one with
cols
rows and
rows
columns.
Apply the commands sequentially from left to right and return the resulting matrix.
Function Signature
def transform_matrix(matrix: list[list[int]], commands: list[str]) -> list[list[int]]:
Rules
-
matrix
is rectangular: every row has the same length.
-
Each command is applied to the result of the previous one, in list order.
-
Return the final matrix as a list of rows. After an odd number of
"T"
commands its shape differs from the input's shape.
Constraints
-
matrix
has
rows
rows and
cols
columns, with
1 <= rows, cols <= 100
-
0 <= matrix[i][j] <= 10^9
-
1 <= len(commands) <= 100
-
Each command is one of
"R"
,
"C"
,
"T"
Examples
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]], commands = ["R"]
Output: [[3,2,1],[6,5,4],[9,8,7]]
Each row is reversed horizontally, so [1,2,3] becomes [3,2,1], and the same happens to the other two rows.
Input: matrix = [[1,2],[3,4]], commands = ["T","R"]
Output: [[3,1],[4,2]]
After "T" the matrix is [[1,3],[2,4]]. Reversing each row then gives [[3,1],[4,2]]. A transpose followed by a row reversal is a 90 degree clockwise rotation.
Input: matrix = [[1,2,3],[4,5,6]], commands = ["T","C"]
Output: [[3,6],[2,5],[1,4]]
After "T" the 2 by 3 matrix becomes the 3 by 2 matrix [[1,4],[2,5],[3,6]]. "C" then reverses the order of its rows. Together the two commands rotate the original matrix 90 degrees counterclockwise.