def __init__(self, g): self.G = g self.marked = [False] * self.G.V self.post = [0] * self.G.V self.pre = [0] * self.G.V # 记录顶点在preorder这个排序中排名第几 self.postorder = Queue1.Queue() # postorder是顶点遍历完成的顺序 self.preorder = Queue1.Queue() # preorder是顶点调用的顺序 self.preCounter = 0 # preCounter是用来统计pre数组中的个数的 self.postCounter = 0 for v in range(self.G.V): # 就是按照顶点标号进行遍历 if not self.marked[v]: self.dfs(v)
def bfs(self, s): # 现将原点放到队列中然后进行对她相邻带你的寻找 #再一一对相邻点进行排查标记路径也进行时最短的路径 q = Queue1.Queue() self.marked[s] = True self.distTo[s] = 0 q.enqueue(s) while not q.isEmpty(): v = q.dequeue() for w in self.G.adj(v): if not self.marked[w]: self.edgeTo[w] = v self.distTo[w] = self.distTo[v] + 1 self.marked[w] = True q.enqueue(w)
def bfs(self): #用广度优先的算法对各个顶点进行遍历 q = Queue1.Queue() for v in range(self.G.V()): self.distTo[v] = sys.maxint self.distTo[self.source] = 0 self.marked[self.source] = True q.enqueue(self.source) while not q.isEmpty(): l = q.dequeue() for w in self.G.adj(l): if not self.marked[w]: self.edgeTo[w] = l self.distTo[w] = self.distTo[l] + 1 self.marked[w] = True q.enqueue(w)
g.addEdge(3, 4) g.addEdge(3, 5) g.addEdge(5, 6) g.addEdge(7, 8) g.addEdge(7, 9) g.addEdge(8, 12) g.addEdge(9, 12) g.addEdge(9, 10) g.addEdge(12, 11) g.addEdge(10, 11) g.addEdge(13, 14) g.addEdge(13, 17) g.addEdge(13, 18) g.addEdge(14, 15) g.addEdge(14, 16) g.addEdge(15, 19) g.addEdge(16, 19) # g.addEdge(16,20) g.addEdge(15, 18) # g.addEdge(18,20) cc = CC(g) m = cc.count() print m + "components" components = Queue1.Queue() for i in range(m): components[i] = Queue1.Queue() for v in range(g.V()): components[cc.id(v)].enqueue(v) for i in range(m): for v in components[i]: print v + ' '