Skip to content

Commit 5b61f3f

Browse files
authored
Merge pull request #145 from AlgorithmStudy-Allumbus/minjeong
Minjeong / 2월 3주차 / 2문제
2 parents 8324e7b + 3e2f6b0 commit 5b61f3f

File tree

2 files changed

+69
-0
lines changed

2 files changed

+69
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import sys
2+
input = sys.stdin.readline
3+
4+
# 입력
5+
N, M = map(int, input().split())
6+
nums = []
7+
for _ in range(N):
8+
nums.append(list(map(int, input().split())))
9+
10+
dp = [[0] * M for _ in range(N)]
11+
12+
# 첫 줄
13+
dp[0][0] = nums[0][0]
14+
for j in range(1, M):
15+
dp[0][j] = dp[0][j - 1] + nums[0][j]
16+
17+
# 왼쪽 누적합 업데이트 -> 오른쪽 누적합 업데이트, 이후 둘 중 더 큰 값으로 업데이트
18+
for i in range(1, N):
19+
20+
left_prefix_sum = [0] * M # 왼쪽 누적합
21+
right_prefix_sum = [0] * M # 오른쪽 누적합
22+
23+
# 왼쪽 누적합
24+
left_prefix_sum[0] = dp[i-1][0] + nums[i][0]
25+
for j in range(1, M):
26+
left_prefix_sum[j] = max(dp[i-1][j], left_prefix_sum[j-1]) + nums[i][j]
27+
28+
# 오른쪽 누적합
29+
right_prefix_sum[M-1] = dp[i-1][M-1] + nums[i][M-1]
30+
for j in range(M-2, -1, -1):
31+
right_prefix_sum[j] = max(dp[i-1][j], right_prefix_sum[j+1]) + nums[i][j]
32+
33+
# DP에 저장
34+
for j in range(M):
35+
dp[i][j] = max(left_prefix_sum[j], right_prefix_sum[j])
36+
37+
# 정답 출력
38+
print(dp[N-1][M-1])
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import sys
2+
3+
sys.setrecursionlimit(10 ** 8)
4+
input = sys.stdin.readline
5+
6+
7+
def dfs(sx, sy):
8+
# 도착 지점에 도달하면 1(한 가지 경우의 수)를 리턴
9+
if sx == m - 1 and sy == n - 1:
10+
return 1
11+
12+
# 이미 방문한 적이 있다면 그 위치에서 출발하는 경우의 수를 리턴
13+
if dp[sx][sy] != -1:
14+
return dp[sx][sy]
15+
16+
ways = 0
17+
for i in range(4):
18+
nx, ny = sx + dx[i], sy + dy[i]
19+
if 0 <= nx < m and 0 <= ny < n and graph[sx][sy] > graph[nx][ny]:
20+
ways += dfs(nx, ny)
21+
22+
dp[sx][sy] = ways
23+
return dp[sx][sy]
24+
25+
26+
m, n = map(int, input().split())
27+
graph = [list(map(int, input().split())) for _ in range(m)]
28+
dp = [[-1] * n for _ in range(m)]
29+
dx, dy = [1, -1, 0, 0], [0, 0, 1, -1]
30+
31+
print(dfs(0, 0))

0 commit comments

Comments
 (0)