assert self.hasPathTo(w), 'There is no path!'
        pathlist = [w]
        currentVert = self.vertDict[w]
        while currentVert != self.startVert:
            currentVert = currentVert.getPred()
            pathlist.append(currentVert.getId())
        pathlist.reverse()
        return pathlist

    def showPath(self, w):
        assert w >= 0 and w < len(self.vertDict)
        assert self.hasPathTo(w), 'There is no path!'
        pathlist = self.shortestPath(w)
        print(pathlist)


g = SparseGraph(directed=True, weighted=True)
buildGraphFromFile(g, 'testDAG.txt')
T = TopologicalSort(g)
DAG = DAGShortestPath(T.getSortedList(), 2)
print(DAG.shortestPathTo(6))
DAG.showPath(6)
'''
这个实现是这样的:
先定义一个类求出DAG的拓扑排序,装在一个list中。
然后再定义一个求DAG最短路径的类,这个类接受一个装载拓扑排序结果的list和源id
这两个类之间没关系,每个类都可以拿出来单独调用。

其实也可以把这两个类的操作合并成一个类,但我懒得考虑如何实现更合理了,反正算法思想已经实现出来了
'''
Example #2
0
        assert w >= 0 and w < len(self.graph.vertDict)
        return self.graph.vertDict[w].visited()

    def shortestPath(self, w):
        assert w >= 0 and w < len(self.graph.vertDict)
        if not self.hasPathTo(w):
            return print('There is no path between %s and %s' %
                         (self.startVert.getId(), w))
        pathlist = [w]
        currentVert = self.graph.vertDict[w]
        while currentVert != self.startVert:
            currentVert = currentVert.getPred()
            pathlist.append(currentVert.getId())
        pathlist.reverse()
        return pathlist

    def showPath(self, w):
        assert w >= 0 and w < len(self.graph.vertDict)
        pathlist = self.shortestPath(w)
        print(pathlist)


g = SparseGraph(directed=True, weighted=True)
buildGraphFromFile(g, 'testG2.txt')
S = Spfa(g, 0)
print(S.shortestPathTo(4))
S.showPath(4)
'''
对于spfa算法来说,检测是否有负权环的方法是:同一个节点进入队列的次数超过N次(N-1次?)。
这里我偷懒了,没有对图的负权环进行检测,所以不要传入带负权环的图去测试。
'''
Example #3
0
class ComponentsCounter(object):
    def __init__(self, aGraph):
        self.graph = aGraph
        self.result = 0
        self.calc()

    def calc(self):  #result store in both graph.ccount and self.result
        for vertex in self.graph:
            vertex.setVisited(False)
        for vertex in self.graph:
            if not vertex.visited():
                self._dfs(vertex, self.graph.getCcount())
                self.graph.setCcount(self.graph.getCcount() + 1)
                self.result += 1

    def _dfs(self, startVertex, ccount):
        startVertex.setCCID(ccount)
        startVertex.setVisited(True)
        for nextVertex in startVertex.getConnections():
            if not nextVertex.visited():
                self._dfs(nextVertex, ccount)

    def getResult(self):
        return self.result


graph = SparseGraph()
buildGraphFromFile(graph, 'testG1.txt')
Counter = ComponentsCounter(graph)
print(Counter.getResult())
print(graph.isConnected(0, 5))