Skip to content

Commit 9f1fc8d

Browse files
committed
feat: 2월 3주차 과제 문제 답변 업로드 (BOJ #1520. 내리막길 (골드3)
1 parent 7fa0c07 commit 9f1fc8d

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

_WeeklyChallenges/W12-[DP]/Assignment_BOJ_1520_내리막길.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,39 @@
44
유형: Dynamic Programming, Graph Theory, Graph Traversal, Depth-First Search
55
'''
66

7+
import sys
8+
sys.setrecursionlimit(10**6)
9+
input = sys.stdin.readline
10+
11+
# 방향 벡터 (상, 하, 좌, 우)
12+
dx = [-1, 1, 0, 0]
13+
dy = [0, 0, -1, 1]
14+
15+
def dfs(x, y):
16+
# 도착점에 도달하면 경로 1개 반환
17+
if x == M - 1 and y == N - 1:
18+
return 1
19+
20+
# 이미 방문한 적이 있다면 저장된 경로 개수 반환
21+
if dp[x][y] != -1:
22+
return dp[x][y]
23+
24+
# 현재 위치에서 가능한 경로 개수 계산
25+
dp[x][y] = 0 # 초기화
26+
for i in range(4):
27+
nx, ny = x + dx[i], y + dy[i]
28+
if 0 <= nx < M and 0 <= ny < N and graph[nx][ny] < graph[x][y]: # 내리막길 조건
29+
dp[x][y] += dfs(nx, ny)
30+
31+
return dp[x][y]
32+
33+
# 입력 처리
34+
M, N = map(int, input().split())
35+
graph = [list(map(int, input().split())) for _ in range(M)]
36+
37+
# DP 배열 (-1로 초기화)
38+
dp = [[-1] * N for _ in range(M)]
39+
40+
# 결과 출력
41+
H = dfs(0, 0)
42+
print(H)

0 commit comments

Comments
 (0)