Given an n x n matrix whose cells hold either the string "X" or an integer written as a string, rotate only the integer values k times while every "X" stays where it is.
The integer cells are ordered by reading order: left to right within a row, and rows from top to bottom. One rotation moves every integer value one position forward in that order, and the value in the last position wraps around to the first position. Return the matrix after k rotations.
Function Signature
def rotate_non_x(matrix: list[list[str]], k: int) -> list[list[str]]:
Rules
-
Each cell is either the exact string
"X"
or the decimal string form of an integer, such as
"7"
or
"-12"
. Values are moved as the same strings and never changed.
-
"X"
cells keep their positions. Only the integer cells take part in the rotation.
-
One rotation is a shift by one position forward in reading order: the value at position
i
of the reading order moves to position
i + 1
, and the last value moves to position 0.
-
If the matrix has no integer cells, return it unchanged.
-
You may modify
matrix
in place and return it, or return a new matrix with the same contents.
Constraints
-
1 <= n <= 10
-
0 <= k <= 1000
-
Every cell is
"X"
or an integer in the range
[-100, 100]
Examples
Input: matrix = [["1","X","3"],["X","5","6"],["7","8","X"]], k = 2
Output: [["7","X","8"],["X","1","3"],["5","6","X"]]
The integer values in reading order are [1, 3, 5, 6, 7, 8]. Two rotations give [7, 8, 1, 3, 5, 6], and writing those back into the six integer cells in reading order produces the output.
Input: matrix = [["X","2"],["3","X"]], k = 1
Output: [["X","3"],["2","X"]]
The values are [2, 3]. One rotation moves 2 to the second integer cell and wraps 3 around to the first.
Input: matrix = [["4","X"],["-1","9"]], k = 7
Output: [["9","X"],["4","-1"]]
There are three integer values, [4, -1, 9], so every three rotations bring them back to where they started. Seven rotations act like one, giving [9, 4, -1].