我遵循与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]
----------