Link: https://programmers.co.kr/learn/courses/30/lessons/12913
땅따먹기 게임을 하려고 합니다. 땅따먹기 게임의 땅(land)은 총 N행 4열로 이루어져 있고, 모든 칸에는 점수가 쓰여 있습니다. 1행부터 땅을 밟으며 한 행씩 내려올 때, 각 행의 4칸 중 한 칸만 밟으면서 내려와야 합니다. 단, 땅따먹기 게임에는 한 행씩 내려올 때, 같은 열을 연속해서 밟을 수 없는 특수 규칙이 있습니다.
예를 들면,
| 1 | 2 | 3 | 5 |
| 5 | 6 | 7 | 8 |
| 4 | 3 | 2 | 1 |
로 땅이 주어졌다면, 1행에서 네번째 칸 (5)를 밟았으면, 2행의 네번째 칸 (8)은 밟을 수 없습니다.
마지막 행까지 모두 내려왔을 때, 얻을 수 있는 점수의 최대값을 return하는 solution 함수를 완성해 주세요. 위 예의 경우, 1행의 네번째 칸 (5), 2행의 세번째 칸 (7), 3행의 첫번째 칸 (4) 땅을 밟아 16점이 최고점이 되므로 16을 return 하면 됩니다.
# 재귀함수로 풀었을때 (런타임 에러가 남)
import sys
sys.setrecursionlimit(1000001)
answer = 0
def rec(K,land,selected):
if K == len(land):
global answer
temp = 0
for i in range(len(selected)):
temp += land[i][selected[i]]
if temp > answer:
answer = temp
else:
for cand in range(4):
if selected[K] != 0:
if cand == selected[K-1]: continue
selected[K] = cand
rec(K+1,land,selected)
selected[K] = -1
def solution(land):
global answer
selected = [-1 for _ in range(len(land))]
rec(0,land,selected)
return answer
재귀함수를 통해서 모든 행열을 확인해 보았을 때 정답은 나오지만, 런타임 에러가 나온다는 것을 확인 할 수 있다. 그래서 동적 프로그래밍을 통해서 풀어보았다.
def solution(land):
for i in range(1,len(land)):
land[i][0] += max(land[i-1][1],land[i-1][2],land[i-1][3])
land[i][1] += max(land[i-1][0],land[i-1][2],land[i-1][3])
land[i][2] += max(land[i-1][0],land[i-1][1],land[i-1][3])
land[i][3] += max(land[i-1][0],land[i-1][1],land[i-1][2])
return max(land[len(land)-1])