我想做一个函数,在有向图中找到最高的分数。我有一个开始节点,不能通过同一个节点两次。我尝试使用递归来获得值的总和,直到我到达一个端点节点。然后我会将我的函数回调到开始节点,并尝试其他选项,直到我点击另一个。等等。你知道吗
我的问题是,当我返回到一个具有多条路径的节点时,该节点的得分值是它可以采用的所有路径的总和。我只想要一条特定路径的和。你知道吗
以下是我目前的代码:
caminho = list()
def maxscore(start, parentals, score):
global caminho
parentals += start + '|'
if len(graph[start]) > 0:
for i in graph[start]:
if i not in parentals.split('|'):
value = graph[start][i]
if value:
score += value
func = maxscore(i, parentals, score)
else:
continue
if func[0] > score:
score = func[0]
caminho = parentals.split('|')
return score, caminho
else:
return score, start
graph = {
'a': {'b': 2, 'c': 4},
'b': {'d': 5},
'c': {'a': 1, 'e': 3},
'd': {'f': 4},
'e': {'b': 2, 'f': 3, 'g': 2},
'f': {},
'g': {}
}
print(maxscore('a', '', 0))
我怎么能让它工作到最后只有最好的分数与路径(卡米尼奥)它采取。你知道吗
对不起,如果我说不清楚的话。有问题尽管问。你知道吗
以下是一种方法:
输出:
注意事项:
maxscore()
返回。你知道吗注:修改代码后,可以缩短一点。
best_i
不是真正需要的,测试if best_i is None
可以被if best_path is None
代替。你知道吗另外,如果需要字符串形式的路径,可以打印(“|”.join(best|path))。你知道吗
您可能希望按值发送score变量,但您是按引用发送的,因此所有可能路径的分数都会添加到该变量中。你知道吗
这是我的方法:
这就是印刷的内容:
您可以看到它如何检查所有可能的路径,然后选择最高分:D
相关问题 更多 >
编程相关推荐