dwrdの回答で示唆されているのと同じ考え方に従っていたので、Python で実装してみました。最初は考えていなかった考慮すべき点がいくつかありますが、最終的には機能するようになったと思います.
これがコードです。確かにいくらか磨きをかける必要がありますが、それは始まりです:
def get_score(M, i, j):
"Get the final score for position [i, j.]"
score = 0
if M[i][j] < 0:
score = -float('inf')
else:
score = M[i][j]
score = score + penalty(M, i - 1, j - 1)
score = score + penalty(M, i - 1, j + 1)
score = score + penalty(M, i + 1, j - 1)
score = score + penalty(M, i + 1, j + 1)
score = score + penalty(M, i - 1, j)
score = score + penalty(M, i, j - 1)
score = score + penalty(M, i + 1, j)
score = score + penalty(M, i, j + 1)
return score
def penalty(M, i, j):
"Calculate the penalty for position [i, j] if any."
if i >= 0 and i < len(M) and j >= 0 and j < len(M[0]):
return (0 if M[i][j] > 0 else M[i][j])
return 0
def calc_scores(M):
"Calculate the scores matrix T."
w = len(M[0])
h = len(M)
T = [[0 for _ in range(w)] for _ in range(h)]
for i in range(h):
for j in range(w):
T[i][j] = get_score(M, i, j)
T[0][0] = 0
T[h - 1][w - 1] = 0
return T
def calc_max_score(A, T):
"Calculate max score."
w = len(A[0])
h = len(A)
S = [[0 for _ in range(w + 1)] for _ in range(h + 1)]
for i in range(1, h + 1):
for j in range(1, w + 1):
S[i][j] = max(S[i - 1][j], S[i][j - 1]) + T[i - 1][j - 1]
# These are for the cases where the road-block
# is in the frontier
if A[i - 1][j - 2] < 0 and i == 1:
S[i][j] = -float('inf')
if A[i - 2][j - 1] < 0 and j == 1:
S[i][j] = -float('inf')
return S
def print_matrix(M):
for r in M:
print r
A = [[0, -4, 8], [1, 1, 0]]
T = calc_scores(A)
S = calc_max_score(A, T)
print '----------'
print_matrix(T)
print '----------'
print_matrix(S)
print '----------'
A = [[0, 1, 1], [4, -4, 8], [1, 1, 0]]
T = calc_scores(A)
S = calc_max_score(A, T)
print '----------'
print_matrix(T)
print '----------'
print_matrix(S)
print '----------'
次の出力が得られます。
----------
[0, -inf, 4]
[-3, -3, 0]
----------
[0, 0, 0, 0]
[0, 0, -inf, -inf]
[0, -3, -6, -6]
----------
----------
[0, -3, -3]
[0, -inf, 4]
[-3, -3, 0]
----------
[0, 0, 0, 0]
[0, 0, -3, -3]
[0, 0, -inf, 1]
[0, -3, -6, 1]
----------