17406번 – 배열돌리기4

1

문제

https://www.acmicpc.net/problem/17406

풀이

코드

from collections import deque
from copy import deepcopy
from itertools import permutations
import math

def minSum(matrix): 
  return min([sum(matrix[i]) for i in range(len(matrix))])

def getCoords(matrix, r, c, s):
  dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
  start, sideLength, count, idx = ((r-s, c-s), s*2, 0, 0)
  coords = []
  while(idx != len(dirs)):
    coords.append(start)
    count += 1
    start = (start[0]+dirs[idx][0], start[1]+dirs[idx][1])
    if count == sideLength: idx, count = (idx+1, 0)
  return coords

def answer():
  global originalMatrix, rotations
  candidates = permutations(rotations, len(rotations))
  _min = math.inf
  for eachCase in candidates:
    matrix = deepcopy(originalMatrix)
    for rcs in eachCase:
      r, c, s = rcs
      while(s > 0):
        coords = getCoords(matrix, r-1, c-1, s)
        values = deque([matrix[y][x] for y,x in coords])
        values.rotate(1)
        for ((y, x), v) in zip(coords, values): matrix[y][x] = v
        s -= 1
    _min = min(_min, minSum(matrix))
  print(_min)
  
n, m, k = map(int, input().split())
originalMatrix = [list(map(int, input().split())) for _ in range(n)]
rotations = [list(map(int, input().split())) for _ in range(k)]
answer()

Add Comment