Given an m x n binary matrix, you can perform operations where each operation cycles (rotates) any single row's elements one position to the left or one position to the right.
Find the minimum total number of operations needed so that at least one column consists entirely of 1s. If it is impossible to achieve this, return -1.
Function Signature
def min_operations(matrix: list[list[int]]) -> int:
Rules
-
Rotating a row left once moves the element at index
j
to index
j - 1
, and the element at index
0
wraps around to index
n - 1
. Rotating a row right once moves the element at index
j
to index
j + 1
, and the element at index
n - 1
wraps around to index
0
.
-
Each operation rotates one row by one position. Rows are rotated independently, and the answer counts every single-step rotation across all rows.
-
If some column is already all
1
s, the answer is
0
.
Constraints
-
1 <= m, n <= 100
-
matrix[i][j]
is either
0
or
1
Examples
Input: matrix = [
[1,0,0],
[0,1,0],
[0,0,1]
]
Output: 2
To make column 0 all 1s, row 0 needs no rotation, row 1 rotates left once and row 2 rotates right once, for a total of 2. Every column has a 1 in only one row, so the other two rows need at least one rotation each, and no column costs less than 2.
Input: matrix = [
[1,1,0,0],
[0,0,1,1],
[1,0,0,1]
]
Output: 1
Rows 0 and 2 already have a 1 in column 0, and row 1 rotates right once to move its 1 from column 3 to column 0. The answer cannot be 0 because no column starts out all 1s.
Input: matrix = [
[1,0],
[0,0]
]
Output: -1
Row 1 has no 1, and rotations only reorder the elements inside a row, so no column can ever become all 1s.