serikov

mini_ceo_1

Aug 6th, 2025
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.87 KB | None | 0 0
  1. def get_all_2x2_positions(n):
  2.     positions = []
  3.     for i in range(n-1):
  4.         for j in range(n-1):
  5.             positions.append((i, j))
  6.     return positions
  7.  
  8. def get_2x2_colors(board, i, j):
  9.     return {
  10.         board[i][j],
  11.         board[i][j+1],
  12.         board[i+1][j],
  13.         board[i+1][j+1]
  14.     }
  15.  
  16. def find_unbalanced_squares(board, n):
  17.     all_colors = {'R', 'G', 'B'}
  18.     unbalanced = []
  19.     for i, j in get_all_2x2_positions(n):
  20.         colors = get_2x2_colors(board, i, j)
  21.         if len(colors) < 3:
  22.             missing = all_colors - colors
  23.             unbalanced.append((i, j, missing))
  24.     return unbalanced
  25.  
  26. def find_best_recolor(board, unbalanced):
  27.     count = {}
  28.     for i, j, missing_colors in unbalanced:
  29.         for mi in missing_colors:
  30.             for di in range(2):
  31.                 for dj in range(2):
  32.                     ii, jj = i + di, j + dj
  33.                     if board[ii][jj] != mi:
  34.                         key = (ii, jj, mi)
  35.                         count[key] = count.get(key, 0) + 1
  36.     if not count:
  37.         return None
  38.     best = max(count, key=count.get)
  39.     return best
  40.  
  41. def recolor_cell(board, i, j, color):
  42.     board[i][j] = color
  43.  
  44. def min_recolorings(board):
  45.     n = len(board)
  46.     changes = 0
  47.     board = [row[:] for row in board]
  48.     while True:
  49.         unbalanced = find_unbalanced_squares(board, n)
  50.         if not unbalanced:
  51.             break
  52.         cell = find_best_recolor(board, unbalanced)
  53.         if not cell:
  54.             break
  55.         i, j, color = cell
  56.         recolor_cell(board, i, j, color)
  57.         changes += 1
  58.     return changes
  59.  
  60. board = [
  61.     ['R', 'B', 'R', 'B', 'R', 'B'],
  62.     ['G', 'R', 'G', 'R', 'G', 'R'],
  63.     ['B', 'G', 'B', 'G', 'B', 'G'],
  64.     ['R', 'B', 'R', 'B', 'R', 'B'],
  65.     ['G', 'R', 'G', 'R', 'G', 'R'],
  66.     ['B', 'G', 'B', 'G', 'B', 'G'],
  67. ]
  68.  
  69. print(min_recolorings(board))
  70.  
Advertisement
Add Comment
Please, Sign In to add comment