Dynamic program example

This commit is contained in:
Jan-Niclas Loosen
2025-10-18 20:34:32 +02:00
commit 49438ccaaf
2 changed files with 41 additions and 0 deletions

39
Uebung-01/perseverance.py Normal file
View File

@@ -0,0 +1,39 @@
data = [
[0, 9, 2, 5, 11, 8],
[17, 21, 32, 5, 15, 3],
[2, 2, 3, 8, 1, 5],
[8, 2, 8, 11, 15, 9],
[0, 5, 3, 10, 4, 0]
]
max_y = len(data)
max_x = len(data[0])
start = (max_y-1, max_x-1)
# Cache with size of n points
cache = [[None for _ in range(max_x)] for _ in range(max_y)]
def find_path(y, x):
if not (0 <= y < max_y and 0 <= x < max_x):
return (), float('-inf')
if cache[y][x] is not None:
return cache[y][x]
if y == 0 and x == 0:
res = (((y, x),), data[y][x])
else:
west_path, west_val = find_path(y, x-1)
north_path, north_val = find_path(y-1, x)
if west_val > north_val:
res = (west_path + ((y, x),), west_val + data[y][x])
else:
res = (north_path + ((y, x),), north_val + data[y][x])
cache[y][x] = res
return res
path, val = find_path(*start)
print(f"Val: {val}")
print(f"Path: {path}")