def testSP(): nodes = [] for name in range(6): nodes.append(str(name)) g = Digraph() for n in nodes: g.addNode(n) g.addEdge(Edge(nodes[0], nodes[1])) g.addEdge(Edge(nodes[1], nodes[2])) g.addEdge(Edge(nodes[2], nodes[3])) g.addEdge(Edge(nodes[2], nodes[4])) g.addEdge(Edge(nodes[3], nodes[4])) g.addEdge(Edge(nodes[3], nodes[5])) g.addEdge(Edge(nodes[0], nodes[2])) g.addEdge(Edge(nodes[1], nodes[0])) g.addEdge(Edge(nodes[3], nodes[1])) g.addEdge(Edge(nodes[4], nodes[0])) sp = search(g, nodes[0], nodes[5]) print "Shortest path by BFS: ", printPath(sp)
class SymbolGraph: """用符号作为顶点名的图,符号图""" def __init__(self, filename, sp): self.st = {} with open(filename, 'r') as f: while True: line = f.readline() if line == '': break line = line.split('\n')[0] for a in line.split(sp): if a not in self.st: self.st[a] = len(self.st) self.keys = [0] * len(self.st) for name in self.st.keys(): self.keys[self.st[name]] = name self.g = Digraph(len(self.st)) with open(filename, 'r') as f: while True: line = f.readline() if line == '': break line = line.split('\n')[0] a = line.split(sp) v = self.st[a[0]] for t in a[1:]: self.g.addEdge(v, self.st[t]) # print(self.st) def contains(self, s): return s in self.st def index(self, s): return self.st[s] def name(self, v): return self.keys[v] def G(self): return self.g
def addEdge(self, edge): Digraph.addEdge(self, edge) rev = Edge(edge.dest, edge.src) Digraph.addEdge(self, rev)
def topoLogical(graph, current): marked[current] = True for w in graph.adj(current): print 'why' print 'w is{w}, current is {current}'.format(w=w, current=current) if not marked[w]: topoLogical(graph, w) if (current > w): print postPoints global postPoints postPoints = [] print '我是分割线' print postPoints postPoints.append(current) if __name__ == "__main__": print '这是一个有环图' secondGraph = Digraph() secondGraph.addEdge(1, 3) secondGraph.addEdge(1, 5) secondGraph.addEdge(3, 2) print secondGraph.vertex # order(secondGraph, 1) topoLogical(secondGraph, 1) print postPoints
# newGraph.addEdge(2, 4) # newGraph.addEdge(4, 3) # # directDFS(newGraph, 3) # startCheckCirle(newGraph) # print hasCirle print '这是一个有环图' secondGraph = Digraph() # secondGraph.addEdge(1, 2) # secondGraph.addEdge(2, 1) # secondGraph.addEdge(2, 4) # secondGraph.addEdge(4, 3) # secondGraph.addEdge(3, 1) secondGraph.addEdge(1, 2) secondGraph.addEdge(1, 5) secondGraph.addEdge(3, 1) secondGraph.addEdge(3, 4) secondGraph.addEdge(4, 3) secondGraph.addEdge(4, 6) secondGraph.addEdge(5, 3) secondGraph.addEdge(5, 4) secondGraph.addEdge(6, 5) print secondGraph.vertex startCheckCirle(secondGraph) print circleStack