Python 基于图寻路算法
程序员文章站
2022-05-21 17:54:05
...
Python 基于图寻路算法
def generatePath(graphMap,start,end,result): path = start[-1] if (path == end): result.append(start) else: for arc in graphMap[path]: if arc not in start: generatePath(graphMap,start+[arc],end,result) def searchGraph(graphMap,start,end): results = [] generatePath(graphMap, [start], end, results) results.sort(key= lambda x:len(x)) return results if __name__ == '__main__': Graph = {'A': ['B', 'C', 'D'], # 构建树 'B': ['E'], 'C': ['D', 'F'], 'D': ['B', 'E', 'G'], 'E': [], 'F': ['D', 'G'], 'G': ['E']} results = searchGraph(Graph,"A","E") for result in results: print(result)
上一篇: SQL语句在数据库中是如何执行的