我想你可以漫步并在此过程中进行备忘录记忆。我使用镜像位集来表示备忘的路径,以便无论从哪个方向构建都能立即识别。这里是Python版本(哈希长度包括从大小为一到六的路径计数):
from sets import Set
def f(a,k):
stack = []
hash = Set([])
best = (0,0) # sum, path
n = len(a)
for y in range(n):
for x in range(n):
stack.append((1 << (n * y + x),y,x,a[y][x],1))
while len(stack) > 0:
(path,y,x,s,l) = stack.pop()
if l == k and path not in hash:
hash.add(path)
if s > best[0]:
best = (s,path)
elif path not in hash:
hash.add(path)
if y < n - 1:
stack.append((path | (1 << (n * (y + 1) + x)),y + 1,x,s + a[y + 1][x],l + 1))
if y > 0:
stack.append((path | (1 << (n * (y - 1) + x)),y - 1,x,s + a[y - 1][x],l + 1))
if x < n - 1:
stack.append((path | (1 << (n * y + x + 1)),y,x + 1,s + a[y][x + 1],l + 1))
if x > 0:
stack.append((path | (1 << (n * y + x - 1)),y,x - 1,s + a[y][x - 1],l + 1))
print best
print len(hash)
输出:
arr = [[31,12,7,1,14]
,[23,98,3,87,1]
,[5,31,8,2,99]
,[12,3,42,17,88]
,[120,2,7,5,7]]
f(arr,6)
"""
(377, 549312) sum, path
1042 hash length
549312 = 00000
01110
11000
10000
"""
更新:这个问题与如何在矩阵中找到M个相邻元素的最大总和类似,我意识到需要对我的建议进行修订,以包括从形状中间部分延伸的形态。以下是我修改后的代码,使用集合来哈希形状。在我看来,DFS应该能够使堆栈大小保持在O(m)
的数量级(尽管搜索空间仍然很大)。
from sets import Set
def f(a,m):
stack = []
hash = Set([])
best = (0,[]) # sum, shape
n = len(a)
for y in range(n):
for x in range(n):
stack.append((a[y][x],Set([(y,x)]),1))
while len(stack) > 0:
s,shape,l = stack.pop()
key = str(sorted(list(shape)))
if l == m and key not in hash:
hash.add(key)
if s > best[0]:
best = (s,shape)
elif key not in hash:
hash.add(key)
for (y,x) in shape:
if y < n - 1 and (y + 1,x) not in shape:
copy = Set(shape)
copy.add((y + 1,x))
stack.append((s + a[y + 1][x],copy,l + 1))
if y > 0 and (y - 1,x) not in shape:
copy = Set(shape)
copy.add((y - 1,x))
stack.append((s + a[y - 1][x],copy,l + 1))
if x < n - 1 and (y,x + 1) not in shape:
copy = Set(shape)
copy.add((y,x + 1))
stack.append((s + a[y][x + 1],copy,l + 1))
if x > 0 and (y,x - 1) not in shape:
copy = Set(shape)
copy.add((y,x - 1))
stack.append((s + a[y][x - 1],copy,l + 1))
print best
print len(hash)
输出:
arr = [[31,12,7,1,14]
,[23,98,3,87,1]
,[5,31,8,2,99]
,[12,3,42,17,88]
,[120,2,7,5,7]]
f(arr,6)
"""
(377, Set([(1, 2), (1, 3), (1, 1), (2, 3), (3, 4), (2, 4)]))
2394 hash length
"""