我正在尝试查找从0、0到N,N矩阵总和最小的路径。我从技术上解决了它,但这并不能扩展。它可以在较小的N x N矩阵上正常工作,但是它会在我正在为其构建的80x80矩阵上放下床,因为它具有(2 * 80)! /(80!* 80!)可能的路径。正在考虑添加另一个内核,但不确定如何在所有递归中使用(我几乎不了解如何添加处理器,所以我不想搞砸)。规则是您只能向下移动或移至右侧列。我将进行一些小调整,例如跟踪最小路径,因此我不会遍历所有路径以求和,然后找到最小路径。但是我怀疑这会对运行时产生影响。有谁知道找到此最小路径的更有效方法?
有关该问题的更多详细信息,请访问https://projecteuler.net/problem=81。
def matrix_path_traverser():
file = 'p081_matrix.txt'
with open(file, 'r') as f:
matrix = []
for line in f:
line = line.rstrip('\n')
line = line.split(',')
numerized_line = [int(x) for x in line]
matrix.append(numerized_line)
class Paths:
paths = []
sums = []
def paths(matrix, row, column, n, path_object, prior_path):
# Append the new matrix value to the path of previous values
# Prior_path is a copy from the previous iteration. This is useful for bifurcating
prior_path.append(matrix[row][column])
# If the traverser hits the far right column, append all values directly below
if column == n - 1:
for y in range(row + 1, n):
prior_path.append(matrix[y][column])
# Append the completed path to the list of possible paths
path_object.paths.append(prior_path)
return
# If the traverser hits the bottom row, append all values directly to the right
elif row == n - 1:
for x in range(column + 1, n):
prior_path.append(matrix[row][x])
path_object.paths.append(prior_path)
return
else:
# If the traverser isn't at the far right column or bottom row, make two moves. One to the right, one down
paths(matrix, row, column + 1, n, path_object, prior_path.copy())
paths(matrix, row + 1, column, n, path_object, prior_path.copy())
# initialize Paths object to collect all paths that will be generated
p = Paths()
# Begin recursion
paths(matrix, 0, 0, len(matrix), p, [])
# Sum all paths
p.sums = [sum(path) for path in p.paths]
# Extract minimum
return min(p.sums)