我有一个有向,无加权,循环图,并且我想使用python查找给出起点的最长路径。我知道这个问题不能在多项式时间内解决,实际上,上面的解决方案还远远不能解决这个问题。
在这里我发现一些代码,为了适应我的需要我做了一些修改。它可以工作,但会存储我从该源节点传播图形时遇到的每条路径,并最终选择最长的一条,条件是端点是我选择的节点之一。 我只想存储符合条件的最长路径,而不是全部存储,那么我想做类似的事情
if islonger and endsWithOutput
longestpath = currentpath
这可能吗?这是代码:
from collections import defaultdict
def DFS(G,v,seen=None,path=None):
if seen is None: seen = []
if path is None: path = [v]
seen.append(v)
paths = []
for t in G[v]:
if t not in seen:
t_path = path + [t]
paths.append(tuple(t_path))
paths.extend(DFS(G, t, seen[:], t_path))
return paths
# Define edges
edges = [['1', '3'], ['2', '3'], ['3', '4'], ['4', '6'],['6','5'],['7','5'],
['5','8'],['5','4']]
# Define outputs
outputs = ['8']
# Build graph
G = defaultdict(list)
for (i,j) in edges:
G[i].append(j)
# starting from '1'
all_paths = DFS(G, '1')
max_len = max(len(p) for p in all_paths if p[-1] in outputs)
max_paths = [p for p in all_paths if len(p) == max_len and p[-1] in outputs]
# Output
print("All Paths:")
print(all_paths)
print("Longest Paths:")
for p in max_paths: print(" ", p)
print("Longest Path Length:")
print(max_len)