python 图实现

 

#coding:utf-8
__author__ = 'similarface'

class Graph:
    def __init__(self,label,extra=None):
        #节点是类实例
        self.name=label
        #而图是由类实例链接而成
        self.data=extra
        self.arcs=[]

    def __repr__(self):
        return self.name

    def search(self,goal):
        Graph.solns=[]
        self.generate([self],goal)
        Graph.solns.sort(key=lambda x:len(x))
        return Graph.solns

    def generate(self, path, goal):
        if self == goal:
            Graph.solns.append(path)
        else:
            for arc in self.arcs:
                if arc not in path:
                    arc.generate(path + [arc], goal)
if __name__=="__main__":
    for name in "ABCDEFG":
        exec("%s = Graph('%s')" % (name, name))
    A.arcs = [B, E, G]
    B.arcs = [C]
    C.arcs = [D, E]
    D.arcs = [F]
    E.arcs = [C, F, G]
    G.arcs = [A]

    A.search(G)

 

posted @ 2016-01-13 22:48  similarface  阅读(442)  评论(0编辑  收藏  举报