Advertisement
kosievdmerwe

Untitled

Sep 26th, 2021
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. class Solution:
  2.     def movesToChessboard(self, board: List[List[int]]) -> int:
  3.         W = len(board)
  4.         H = len(board[0])
  5.        
  6.         rows = board
  7.         cols = [[board[x][y] for x in range(W)] for y in range(H)]
  8.  
  9.         def _check_valid(lines: List[List[int]]) -> bool:
  10.             c = Counter(line[0] for line in lines)
  11.             if abs(c[0] - c[1]) > 1:
  12.                 return False
  13.            
  14.             for i in range(1, len(lines)):
  15.                 delta = 1 if lines[0][0] != lines[i][0] else 0
  16.                 for j in range(1, len(lines[0])):
  17.                     if (delta + lines[0][j]) % 2 != lines[i][j]:
  18.                         return False
  19.             return True
  20.        
  21.         if not _check_valid(rows) or not _check_valid(cols):
  22.             return -1
  23.        
  24.         def _min_swaps(lines: List[List[int]]) -> int:
  25.             cnt = 0
  26.             expected = 0
  27.             for c in lines[0]:
  28.                 if c != expected:
  29.                     cnt += 1
  30.                 expected = (expected + 1) % 2
  31.             ans_cands = [cnt, len(lines[0]) - cnt]
  32.             ans_cands = [ans for ans in ans_cands if ans % 2 == 0]
  33.             assert ans_cands, "Should have at least one candidate"
  34.             return min(ans_cands) // 2
  35.                
  36.         return _min_swaps(rows) + _min_swaps(cols)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement