파이썬 알고리즘 : 땅따먹기

DP

2023년 12월 11일 알고리즘 문제풀이

문제

땅따먹기

난이도

Lv.2

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def solution(land):
    n = len(land)
    answer = 0
    dp = [[0 for _ in range(4)] for _ in range(n)]
    dp[0] = land[0]
    
    def check(next_row,next_col):
        arr = []
        for i in range(4):
            if i == next_col:
                continue
            arr.append(dp[next_row-1][i])
        return max(arr)

    x = 1
    while x < n:
        for i in range(4):
            dp[x][i] = check(x,i) + land[x][i]
        x += 1
    answer = max(dp[-1])
    return answer

각 행에는 4개의 열이 있다. 각 열에 올 수 있는 방법의 경우는 3가지이다. 예를 들어 2행 0열에 오는 방법은 2행 1열, 2행 2열, 2행 3열에서 오는 것이다. 이러한 원리를 바탕으로 DP를 설정했다.