欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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)