1
class Solution(object):
2
def movesToChessboard(self, board):
3
N = len(board)
4
ans = 0
5
# For each count of lines from {rows, columns}...
6
for count in (
7
collections.Counter(map(tuple, board)), # get row
8
collections.Counter(zip(*board)),
9
): # get column
10

11
# If there are more than 2 kinds of lines,
12
# or if the number of kinds is not appropriate ...
13
if len(count) != 2 or sorted(count.values()) != [N / 2, (N + 1) / 2]:
14
return -1
15

16
# If the lines are not opposite each other, impossible
17
line1, line2 = count
18
if not all(x ^ y for x, y in zip(line1, line2)):
19
return -1
20

21
# starts = what could be the starting value of line1
22
# If N is odd, then we have to start with the more
23
# frequent element
24
starts = [int(line1.count(1) * 2 > N)] if N % 2 else [0, 1]
25

26
# To transform line1 into the ideal line [i%2 for i ...],
27
# we take the number of differences and divide by two
28
ans += (
29
min(
30
sum((x - i) % 2 for i, x in enumerate(line1, start))
31
for start in starts
32
)
33
/ 2
34
)
35

36
return ans

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0