forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.py
41 lines (40 loc) · 1.53 KB
/
Solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution:
def movesToChessboard(self, board: List[List[int]]) -> int:
def f(mask, cnt):
ones = mask.bit_count()
if n & 1:
if abs(n - 2 * ones) != 1 or abs(n - 2 * cnt) != 1:
return -1
if ones == n // 2:
return n // 2 - (mask & 0xAAAAAAAA).bit_count()
return (n + 1) // 2 - (mask & 0x55555555).bit_count()
else:
if ones != n // 2 or cnt != n // 2:
return -1
cnt0 = n // 2 - (mask & 0xAAAAAAAA).bit_count()
cnt1 = n // 2 - (mask & 0x55555555).bit_count()
return min(cnt0, cnt1)
n = len(board)
mask = (1 << n) - 1
rowMask = colMask = 0
for i in range(n):
rowMask |= board[0][i] << i
colMask |= board[i][0] << i
revRowMask = mask ^ rowMask
revColMask = mask ^ colMask
sameRow = sameCol = 0
for i in range(n):
curRowMask = curColMask = 0
for j in range(n):
curRowMask |= board[i][j] << j
curColMask |= board[j][i] << j
if curRowMask not in (rowMask, revRowMask) or curColMask not in (
colMask,
revColMask,
):
return -1
sameRow += curRowMask == rowMask
sameCol += curColMask == colMask
t1 = f(rowMask, sameRow)
t2 = f(colMask, sameCol)
return -1 if t1 == -1 or t2 == -1 else t1 + t2