好的,由于要尝试使用的数据结构,我遇到了很多麻烦,因为原始连接图中有重复项。
更好的是使用这样的数据结构:
connections = {1: [4, 5], 2: [5], 3: [4], 4: [1, 3, 5], 5: [1, 2, 4]}
然后可以从https://www.python.org/doc/essays/graphs/使用以下两种算法
def find_path(graph, start, end, path=[]): path = path + [start] if start == end: return path if not graph.has_key(start): return None for node in graph[start]: if node not in path: newpath = find_path(graph, node, end, path) if newpath: return newpath return None
和完整的路径
def find_all_paths(graph, start, end, path=[]): path = path + [start] if start == end: return [path] if not graph.has_key(start): return [] paths = [] for node in graph[start]: if node not in path: newpaths = find_all_paths(graph, node, end, path) for newpath in newpaths: paths.append(newpath) return paths
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)