1.递归方式
求最短,最终状态即右下角
f(v, i, j) = min(f(v, i - 1, j), f(v, i, j - 1)) + v[i][j]
最长只需将min改为max即可
import numpy as np
# i:行
# j:列
# v:矩阵
def f(v, i, j):
if i == 0 and j == 0:
return v[0][0]
elif i == 0:
return f(v, i, j - 1) + v[i][j]
elif j == 0:
return f(v, i - 1, j) + v[i][j]
else:
return min(f(v, i - 1, j), f(v, i, j - 1)) + v[i][j]
v = np.array([[1, 3, 5, 9], [8, 1, 3,