Algorithm (PS)

백준 17406번: 배열 돌리기 4 (Python/파이썬)

minjiwoo 2022. 12. 24. 17:02
728x90

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

 

17406번: 배열 돌리기 4

크기가 N×M 크기인 배열 A가 있을때, 배열 A의 값은 각 행에 있는 모든 수의 합 중 최솟값을 의미한다. 배열 A가 아래와 같은 경우 1행의 합은 6, 2행의 합은 4, 3행의 합은 15이다. 따라서, 배열 A의

www.acmicpc.net

from itertools import permutations
import copy
import sys

input = sys.stdin.readline
n, m, k = map(int, input().split())
array = []
for i in range(n):
    array.append(list(map(int, input().split())))

# 배열 돌리기
def turn(r, c, s):
    global temp_array
    x1, y1 = r-s, c-s # left top
    x2, y2 = r+s, c+s # right bottom
    while True:
        if x1 == x2 and y1 == y2:
            break
        temp = temp_array[x1][y1]
        # left
        for i in range(x1, x2):
            move = temp_array[i+1][y1]
            temp_array[i][y1] = move

        # bottom
        for i in range(y1, y2):
            move = temp_array[x2][i+1]
            temp_array[x2][i] = move

        # right
        for i in range(x2, x1, -1):
            move = temp_array[i-1][y2]
            temp_array[i][y2] = move

        #top
        for i in range(y2, y1, -1):
            move = temp_array[x1][i-1]
            temp_array[x1][i] = move
        temp_array[x1][y1+1] = temp
        x1 += 1
        y1 += 1
        x2 -= 1
        y2 -= 1


turns = []
# 연산 정보
for _ in range(k):
    r, c, s = map(int, input().split())
    turns.append((r-1, c-1, s))

answer = int(1e9)

def get_min_value(temp_array):
    return min([sum(row) for row in temp_array])

# 연산 순서 정해주기
for line_up in permutations(turns, k):
    temp_array = copy.deepcopy(array)
    for data in line_up:
        r, c, s = data
        turn(r, c, s)
        # get value of the array
    answer = min(answer, get_min_value(temp_array))

print(answer)
728x90