Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ODD_BITS = 0b0101_0101_0101_0101_0101_0101_0101_0101
- EVEN_BITS = ODD_BITS * 2
- class Solution:
- def movesToChessboard(self, board: List[List[int]]) -> int:
- W = len(board)
- H = len(board[0])
- def _to_bits(arr) -> int:
- ans = 0
- for a in arr:
- ans = ans * 2 + a
- return ans
- def _count_bits(i) -> int:
- return bin(i).count("1")
- rows = list(map(_to_bits, board))
- cols = [_to_bits(board[x][y] for x in range(W)) for y in range(H)]
- def _check_valid(lines: List[int], line_len: int) -> bool:
- c = Counter(lines)
- if len(c) != 2:
- return False
- a, b = tuple(c.keys())
- if abs(c[a] - c[b]) > 1:
- return False
- if a & b != 0:
- return False
- if _count_bits(a | b) != line_len:
- return False
- return True
- if not _check_valid(rows, W) or not _check_valid(cols, H):
- return -1
- def _min_swaps(lines: List[int], line_len: int) -> int:
- cnt = _count_bits((lines[0] ^ ODD_BITS) & ((1 << line_len) - 1))
- ans_cands = [cnt, line_len - cnt]
- ans_cands = [ans for ans in ans_cands if ans % 2 == 0]
- assert ans_cands, "Should have at least one candidate"
- return min(ans_cands) // 2
- return _min_swaps(rows, W) + _min_swaps(cols, H)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement