Advertisement
kosievdmerwe

Untitled

Sep 26th, 2021
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.55 KB | None | 0 0
  1. ODD_BITS = 0b0101_0101_0101_0101_0101_0101_0101_0101
  2. EVEN_BITS = ODD_BITS * 2
  3.  
  4. class Solution:
  5.     def movesToChessboard(self, board: List[List[int]]) -> int:
  6.         W = len(board)
  7.         H = len(board[0])
  8.        
  9.         def _to_bits(arr) -> int:
  10.             ans = 0
  11.             for a in arr:
  12.                 ans = ans * 2 + a
  13.             return ans
  14.        
  15.         def _count_bits(i) -> int:
  16.             return bin(i).count("1")
  17.        
  18.         rows = list(map(_to_bits, board))
  19.         cols = [_to_bits(board[x][y] for x in range(W)) for y in range(H)]
  20.  
  21.         def _check_valid(lines: List[int], line_len: int) -> bool:
  22.             c = Counter(lines)
  23.             if len(c) != 2:
  24.                 return False
  25.            
  26.             a, b = tuple(c.keys())
  27.             if abs(c[a] - c[b]) > 1:
  28.                 return False
  29.             if a & b != 0:
  30.                 return False
  31.             if _count_bits(a | b) != line_len:
  32.                 return False
  33.            
  34.             return True
  35.        
  36.         if not _check_valid(rows, W) or not _check_valid(cols, H):
  37.             return -1
  38.        
  39.         def _min_swaps(lines: List[int], line_len: int) -> int:
  40.             cnt = _count_bits((lines[0] ^ ODD_BITS) & ((1 << line_len) - 1))
  41.             ans_cands = [cnt, line_len - cnt]
  42.             ans_cands = [ans for ans in ans_cands if ans % 2 == 0]
  43.             assert ans_cands, "Should have at least one candidate"
  44.             return min(ans_cands) // 2
  45.                
  46.         return _min_swaps(rows, W) + _min_swaps(cols, H)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement