[BaekJoon Online Judge] 12100 – 2048 (Easy)
문제
https://www.acmicpc.net/problem/12100
소스코드
문제에서 최대 다섯 번의 방향 전환이 가능하다고 제약을 걸었기 때문에, 5중 루프를 돌려서 가능한 모든 경우의 수를 만들었다.
앞서 만든 경우에 수에 대해, 문제에서 설명한 2048 게임룰(방향 전환에 따라 블록이 합쳐지는 조건)을 노가다로 작성해서 문제를 해결할 수 있었다.
from copy import deepcopy
def game(direction):
global b
if direction == 0: # 오른쪽
for i in range(N):
tmp = []
for j in range(N):
if b[i][j] != 0:
tmp.append(b[i][j])
for _ in range(N-len(tmp)):
tmp.insert(0,0)
b[i] = tmp
for i in range(N):
for j in range(N-1,0,-1):
if b[i][j] == b[i][j-1]:
b[i][j] *= 2
for k in range(j-1,0,-1):
tmp = b[i][k]
b[i][k] = b[i][k-1]
b[i][k-1] = tmp
b[i][0] = 0
if direction == 1: # 아랫쪽
for i in range(N):
tmp = []
for j in range(N):
if b[j][i] != 0:
tmp.append(b[j][i])
for j in range(N-len(tmp)):
b[j][i] = 0
for j in range(N-len(tmp),N):
b[j][i] = tmp.pop(0)
for i in range(N):
for j in range(N-1,0,-1):
if b[j][i] == b[j-1][i]:
b[j][i] *= 2
for k in range(j-1,0,-1):
tmp = b[k][i]
b[k][i] = b[k-1][i]
b[k-1][i] = tmp
b[0][i] = 0
if direction == 2: # 왼쪽
for i in range(N):
tmp = []
for j in range(N):
if b[i][j] != 0:
tmp.append(b[i][j])
for _ in range(N-len(tmp)):
tmp.append(0)
b[i] = tmp
for i in range(N):
for j in range(N-1):
if b[i][j] == b[i][j+1]:
b[i][j] *= 2
for k in range(j+1,N-1):
tmp = b[i][k]
b[i][k] = b[i][k+1]
b[i][k+1] = tmp
b[i][N-1] = 0
if direction == 3: # 윗쪽
for i in range(N):
tmp = []
for j in range(N):
if b[j][i] != 0:
tmp.append(b[j][i])
k = len(tmp)
for j in range(k):
b[j][i] = tmp.pop(0)
for j in range(k,N):
b[j][i] = 0
for i in range(N):
for j in range(N-1):
if b[j][i] == b[j+1][i]:
b[j][i] *= 2
for k in range(j+1,N-1):
tmp = b[k][i]
b[k][i] = b[k+1][i]
b[k+1][i] = tmp
b[N-1][i] = 0
N = int(input())
block = [list(map(int,input().split())) for _ in range(N)]
case = []
for i in range(4):
for j in range(4):
for k in range(4):
for l in range(4):
for m in range(4):
case.append([i,j,k,l,m])
ans = 0
for c in case:
b = deepcopy(block)
for direction in c: game(direction)
tmp = 0
for i in range(N):
for j in range(N):
if b[i][j] > tmp:
tmp = b[i][j]
if tmp > ans:
ans = tmp
print(ans)