반응형
from itertools import product
from copy import deepcopy
def combine(li):
i, count = 1, 0
res = []
while i < len(li):
if li[i - 1] == li[i] != 0:
res.append(li[i] * 2)
count += 2
i += 1
else:
res.append(li[i - 1])
count += 1
i += 1
if len(li) > count:
res.append(li[-1])
return res
def up(board):
res = [[0] * n for _ in range(n)]
for i in range(n):
temp = []
for j in range(n):
if board[j][i] > 0:
temp.append(board[j][i])
temp = combine(temp)
temp += [0] * (n - len(temp))
for j in range(n):
res[j][i] = temp[j]
return res
def down(board):
res = [[0] * n for _ in range(n)]
for i in range(n):
temp = []
for j in range(n - 1, -1, -1):
if board[j][i] > 0:
temp.append(board[j][i])
temp = combine(temp)
temp += [0] * (n - len(temp))
temp = temp[::-1]
for j in range(n):
res[j][i] = temp[j]
return res
def left(board):
res = []
for i in range(n):
temp = []
for j in range(n):
if board[i][j] > 0:
temp.append(board[i][j])
temp = combine(temp)
temp += [0] * (n - len(temp))
res.append(temp)
return res
def right(board):
res = []
for i in range(n):
temp = []
for j in range(n - 1, -1, -1):
if board[i][j] > 0:
temp.append(board[i][j])
temp = combine(temp)
temp += [0] * (n - len(temp))
res.append(temp[::-1])
return res
def move(board, d):
if d == 0:
return up(board)
elif d == 1:
return down(board)
elif d == 2:
return left(board)
elif d == 3:
return right(board)
n = int(input())
board = [list(map(int, input().split())) for _ in range(n)]
ans = 0
pro = list(product([0, 1, 2, 3], repeat=5))
for p in pro:
cur = deepcopy(board)
for d in p:
cur = move(cur, d)
ans = max(*sum(cur, []), ans)
print(ans)
완전탐색
1. product를 통해 모든 경우의 수 생성
2. 수를 합치는 combine을 이용해 각 방향별로 함수 생성
3. 최대값 출력
최적화하면 아마 다음문제들도 풀리지 않을까 싶은데 어려움.,