문제) 백준 - 동적 계획법 (Dynamic Programming) - 내리막 길
-> www.acmicpc.net/problem/1520
1520번: 내리막 길
여행을 떠난 세준이는 지도를 하나 구하였다. 이 지도는 아래 그림과 같이 직사각형 모양이며 여러 칸으로 나뉘어져 있다. 한 칸은 한 지점을 나타내는데 각 칸에는 그 지점의 높이가 쓰여 있으
www.acmicpc.net
각 지점까지 이동할 수 있는 경로의 수를 저장한 2차원 리스트(dist)에 메모이제이션을 적용한다. dist 리스트의 초기값을 -1로 선언해 방문 여부를 판단한다. 각 지점까지 이동할 수 있는 경우의 수는 dfs를 이용하여 경로가 겹치는 지점에서 서로의 경로 수를 합친다.
Python 소스 코드)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def dfs(x, y): | |
# 기저 사례 | |
if x == 0 and y == 0: | |
return 1 | |
if dist[x][y] == -1: | |
dist[x][y] = 0 | |
for i in range(4): | |
nx, ny = x + dx[i], y + dy[i] | |
if 0 <= nx < m and 0 <= ny < n: | |
if graph[x][y] < graph[nx][ny]: | |
dist[x][y] += dfs(nx, ny) | |
return dist[x][y] |
C++ 소스 코드)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int m, n; | |
int board[MAX][MAX]; | |
int cache[MAX][MAX]; | |
int dfs(int x, int y) { | |
if (x == 0 && y == 0) return 1; | |
int& ret = cache[x][y]; | |
if (ret != -1) return ret; | |
ret = 0; | |
for (int i = 0; i < 4; ++i) { | |
int nx = x + Dir[i].first; | |
int ny = y + Dir[i].second; | |
if (0 <= nx && nx < m && 0 <= ny && ny < n) | |
if(board[nx][ny] > board[x][y]) | |
ret += dfs(nx, ny); | |
} | |
return ret; | |
} |
Python Full Code)
GitHub - Chocochip101/BOJ_Solution
Contribute to Chocochip101/BOJ_Solution development by creating an account on GitHub.
github.com
C++ Full Code)
GitHub - Chocochip101/BOJ_Solution
Contribute to Chocochip101/BOJ_Solution development by creating an account on GitHub.
github.com
반응형
'PS(Problem Solving) > 백준_BOJ' 카테고리의 다른 글
[백준] 11722번 - 가장 긴 감소하는 부분 수열 (C++, 파이썬) 문제 및 풀이 (0) | 2021.03.09 |
---|---|
[백준] 1890번 - 점프 (파이썬) 문제 및 풀이 (0) | 2021.03.09 |
[백준] 1904번 - 01타일 (C++/파이썬) 문제 및 풀이 (0) | 2021.03.04 |
[백준] 14502번 - 연구소 (파이썬) 문제 및 풀이 (0) | 2021.03.03 |
[백준] 11053번 - 가장 긴 증가하는 부분 수열 (파이썬) (0) | 2021.03.02 |
댓글