码迷,mamicode.com
首页 > 其他好文 > 详细

数据结构-图

时间:2020-01-08 00:53:05      阅读:52      评论:0      收藏:0      [点我收藏+]

标签:png   int   图片   ==   image   info   sea   star   rap   

有向图

技术图片

 

# -*- coding:utf-8 -*-
def searchGraph(graph, start, end):
    results = []
    generatePath(graph, [start], end, results)
    results.sort(key=lambda x:len(x))#按元素长度升序排序
    return results
def generatePath(graph, path, end, results):
    state = path[-1]
    if state == end:
        results.append(path)
    else:
        for arc in graph[state]:
            if arc not in path:
                generatePath(graph, path + [arc], end, results)
if __name__ == __main__:
    Graph = {A:  [B, C, D],
             B:  [E],
             C:  [D, F],
             D:  [B, E, G],
             E:  [],
             F:  [D, G],
             G:  [E]}
    r = searchGraph(Graph, A,D)
    print(************************)
    print(     path A to D)
    print(************************)
    for i in r:
        print(i)
    r = searchGraph(Graph, A,E)
    print(************************)
    print(     path A to E)
    print(************************)
    for i in r:
        print(i)
    r = searchGraph(Graph, C,E)
    print(************************)
    print(     path C to E)
    print(************************)
    for i in r:
        print(i)
************************
     path A to D
************************
[A, D]
[A, C, D]
[A, C, F, D]
************************
     path A to E
************************
[A, B, E]
[A, D, E]
[A, C, D, E]
[A, D, B, E]
[A, D, G, E]
[A, C, D, B, E]
[A, C, D, G, E]
[A, C, F, D, E]
[A, C, F, G, E]
[A, C, F, D, B, E]
[A, C, F, D, G, E]
************************
     path C to E
************************
[C, D, E]
[C, D, B, E]
[C, D, G, E]
[C, F, D, E]
[C, F, G, E]
[C, F, D, B, E]
[C, F, D, G, E]

数据结构-图

标签:png   int   图片   ==   image   info   sea   star   rap   

原文地址:https://www.cnblogs.com/pfeiliu/p/12164168.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!