美文网首页
Python数据结构实现图

Python数据结构实现图

作者: 狗子渣渣 | 来源:发表于2016-01-16 10:36 被阅读1353次

    图是由边或者弧连接起来的节点的网络。在有向图中,节点之间的连接是有方向的,叫做弧(arcs)。在无向图中,节点间的连接没有方向,叫做边(edge)。图算法包括查找两点间路径、两点间的最短路径、判断一个图中是否存在环(环是从一个节点可以沿一条非空路径回到它自己)、找到可以遍历所有节点的路径(著名的TSP问题,即旅行商问题)等等

    图的实现

    在Python中,图主要是通过列表和词典来构造。比如说下面这张图,

         A --> B
         A --> C
         B --> C
         B --> D
         C --> D
         D --> C
         E --> F
         F --> C
    

    就是通过下面这个字典和列表的结合进行构造

        graph = {'A': ['B', 'C'],
                 'B': ['C', 'D'],
                 'C': ['D'],
                 'D': ['C'],
                 'E': ['F'],
                 'F': ['C']}
    

    源代码

    # -*- encoding:utf-8 -*-
    '''
    
     A --> B
     A --> C
     B --> C
     B --> D
     C --> D
     D --> C
     E --> F
     F --> C
    
    '''
    
    
    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 path
    
    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
    
    def find_shortest_path(graph, start, end, path=[]):
            '查找最短路径'
            path = path + [start]
            if start == end:
                return path
            if not graph.has_key(start):
                return None
            shortest = None
            for node in graph[start]:
                if node not in path:
                    newpath = find_shortest_path(graph, node, end, path)
                    if newpath:
                        if not shortest or len(newpath) < len(shortest):
                            shortest = newpath
            return shortest
    
    #test
    
    if __name__ == '__main__':
        graph = {'A': ['B', 'C'],
                 'B': ['C', 'D'],
                 'C': ['D'],
                 'D': ['C'],
                 'E': ['F'],
                 'F': ['C']}
        print find_path(graph,'A','D')
        print find_all_paths(graph,'A','D')
        print find_shortest_path(graph,'A','D')

    相关文章

      网友评论

          本文标题:Python数据结构实现图

          本文链接:https://www.haomeiwen.com/subject/zbihkttx.html