[동적 계획법, 그래프] JUMPGAME 외발 뛰기

2021. 1. 6. 17:55알고리즘/알고리즘 문제 [medium]

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <cstring>
 
#define UNTRAVELED -1
#define NO 0
#define YES 1
 
int cache[100][100];
int board[100][100];
int dy[2]{1,0};
int dx[2]{0,1};
 
bool inRange(int y, int x, int n)
{
    return ((y < n) && (x < n));
}
 
int jump(int y, int x, int n)
{
    int &ret{cache[y][x]}, nexty{}, nextx{};
    
    if(board[y][x] == 0return YES;
    if(ret != UNTRAVELED) return ret;
    
    ret = NO;
    for(int i{0}; i < 2; i++)
    {
        nexty = y + dy[i] * board[y][x]; nextx = x + dx[i]*board[y][x];
        if(inRange(nexty,nextx,n) && !ret)
            ret = jump(nexty, nextx, n);
    }
 
    return ret;
}
 
int main(void)
{
    int testCase = 0, n = 0;
    std::cin>>testCase;
    
    for(int i{0}; i < testCase; i++)
    {
        std::cin>>n;
        memset(cache, -1sizeof cache);
        for(int j{0}; j < n; j++)
        {
            for(int k {0}; k < n; k++)
            {
                std::cin>>board[j][k];
            }            
        }
        if(jump(00, n) == YES)
            std::cout<<"YES"<<std::endl;
        else
            std::cout<<"NO"<<std::endl;
    }
}
 
 

1. 동적 게획법 메모이제이션

    다음 좌표로부터 답을 도출할 수 있는지를 기록하는 cache 배열을 만들었다.

    책에서는 반복문이 아니라 비교문을 리턴하여 답을 도출했다.

    return ret = (jump(아래쪽) || jump(오른쪽);

 

2. 기저사례

    끝지점인 board[n-1][n-1]에 도착했을 때

    한번 방문했던 좌표일때

    (책에서는 배열 범위에 벗어났을 때)

 

3. 다른 해법

    그래프로 모델링하면 간단한 문제가 된다.

 

- 알고리즘 문제해결전략 218p

JUMPGAME