You are given two integers n and m representing the number of rows and columns of a matrix grid. The matrix is initially filled such that grid[i][j] = i * m + j + 1 for every 0 <= i < n and 0 <= j < m (values from 1 to n * m filled row by row).
You are also given a 2D array commands, where each command is one of the following:
-
[1, r1, r2]
: swap rows
r1
and
r2
.
-
[2, c1, c2]
: swap columns
c1
and
c2
.
-
[3, r, v]
: set every cell in row
r
to value
v
.
-
[4, c, v]
: set every cell in column
c
to value
v
.
Apply each command in order and return the final matrix.
Function Signature
def apply_commands(n: int, m: int, commands: list[list[int]]) -> list[list[int]]:
...
Rules
-
Row and column indices are 0-based and refer to positions in the matrix as it stands after all earlier commands.
-
A swap with two equal indices leaves the matrix unchanged.
-
Return the matrix as a list of
n
rows, each a list of
m
integers.
Constraints
-
1 <= n, m <= 100
-
1 <= commands.length <= 1000
-
Row indices are in
[0, n - 1]
and column indices are in
[0, m - 1]
.
-
0 <= v <= 10^9
Examples
Input: n = 3, m = 3, commands = [[1,0,2],[3,1,9]]
Output: [[7,8,9],[9,9,9],[1,2,3]]
The initial matrix is [[1,2,3],[4,5,6],[7,8,9]]. Swapping rows 0 and 2 gives [[7,8,9],[4,5,6],[1,2,3]], and setting row 1 to 9 replaces the middle row.
Input: n = 2, m = 4, commands = [[2,0,3],[4,1,0]]
Output: [[4,0,3,1],[8,0,7,5]]
The initial matrix is [[1,2,3,4],[5,6,7,8]]. Swapping columns 0 and 3 gives [[4,2,3,1],[8,6,7,5]], and setting column 1 to 0 replaces the 2 and the 6.
Input: n = 2, m = 2, commands = [[4,0,5],[2,0,1]]
Output: [[2,5],[4,5]]
Setting column 0 to 5 gives [[5,2],[5,4]]. The column swap then moves the column of 5s to position 1 and the original column [2, 4] to position 0.