Baekjoon 1520

DP, DFS

Baekjoon 1520

Description

여행을 떠난 세준이는 지도를 하나 구하였다. 이 지도는 아래 그림과 같이 직사각형 모양이며 여러 칸으로 나뉘어져 있다. 한 칸은 한 지점을 나타내는데 각 칸에는 그 지점의 높이가 쓰여 있으며, 각 지점 사이의 이동은 지도에서 상하좌우 이웃한 곳끼리만 가능하다.

현재 제일 왼쪽 위 칸이 나타내는 지점에 있는 세준이는 제일 오른쪽 아래 칸이 나타내는 지점으로 가려고 한다. 그런데 가능한 힘을 적게 들이고 싶어 항상 높이가 더 낮은 지점으로만 이동하여 목표 지점까지 가고자 한다.

지도가 주어질 때 이와 같이 제일 왼쪽 위 지점에서 출발하여 제일 오른쪽 아래 지점까지 항상 내리막길로만 이동하는 경로의 개수를 구하는 프로그램을 작성하시오.

Input

첫째 줄에는 지도의 세로의 크기 M과 가로의 크기 N이 빈칸을 사이에 두고 주어진다. 이어 다음 M개 줄에 걸쳐 한 줄에 N개씩 위에서부터 차례로 각 지점의 높이가 빈 칸을 사이에 두고 주어진다. M과 N은 각각 500이하의 자연수이고, 각 지점의 높이는 10000이하의 자연수이다.

Output

첫째 줄에 이동 가능한 경로의 수 H를 출력한다. 모든 입력에 대하여 H는 10억 이하의 음이 아닌 정수이다.

Example I & O

Input 1
4 5
50 45 37 32 30
35 50 40 20 25
30 30 25 17 28
27 24 22 15 10

Output 1
3

My solution

dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
M, N = map(int, input().split())
graph = [[0] * (N + 1)]
dp = [[0] * (N + 1) for i in range(M + 1)]

for i in range(M):
    l = [0]
    l.extend(list(map(int, input().split())))
    graph.append(l)

def DFS(graph, x, y, visited = []):
    count = 0
    visited.append((x, y))
    if x == N and y == M:
        dp[y][x] = 1
        return

    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]

        if nx < 1 or nx > N or ny < 1 or ny > M:
            continue
        else:
            if graph[ny][nx] < graph[y][x]:
                if (nx, ny) in visited:
                    count += dp[ny][nx]
                else:
                    DFS(graph, nx, ny, visited)
                    count += dp[ny][nx]

    dp[y][x] = count

DFS(graph, 1, 1)
print(dp[1][1])
  • Sketch
    Only DFS → time inefficient
    We should use both DFS and DP
    dp[i][j] : the number of path from coordinate (j, i) to (M, N) in graph
    We use Top-down method of dynamic programming

  • Code Analysis

dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
M, N = map(int, input().split())
graph = [[0] * (N + 1)]
dp = [[0] * (N + 1) for i in range(M + 1)]

for i in range(M):
    l = [0]
    l.extend(list(map(int, input().split())))
    graph.append(l)

dx, dy : movement for next node
M : maximum y coordinate of graph
N : maximum x coordinate of graph
Foramtion of dp table and graph


def DFS(graph, x, y, visited = []):
    count = 0
    visited.append((x, y))
    if x == N and y == M:
        dp[y][x] = 1
        return

Implementation of DFS : Recursion function
DFS function doesn’t have the return value, but has side effect : dp[y][x] setting
count : (x, y)’s value in dp table
visited.append() : memorization of visiting coordinate (calculated coordinate for dp value)
dp[M][N] == 1 : Stop case of recursion function


for i in range(4):
    nx = x + dx[i]
    ny = y + dy[i]

    if nx < 1 or nx > N or ny < 1 or ny > M:
        continue

Node movement


else:
    if graph[ny][nx] < graph[y][x]:
        if (nx, ny) in visited:
            count += dp[ny][nx]
        else:
            DFS(graph, nx, ny, visited)
            count += dp[ny][nx]

dp[y][x] = count

reference to DP post : top-down for fibonacci
There must be repeating path
visited DP coordinate : not execute in DFS, but just use the dp value
not visited DP coordinate : execute in DFS
final purpose of DFS function : dp[y][x] setting


DFS(graph, 1, 1)
print(dp[1][1])

dp[1][1] setting by DFS
print the result (dp[1][1])

Best answer

answer


© 2017. All rights reserved.

Powered by Hydejack v조현진