图的遍历(python实现)

深度优先遍历

深度优先遍历顾名思义就是一条路走到黑,如图所示,从0开始遍历,遍历他的邻边1,当遍历1时,发现他的邻边0已经遍历了,所以这条路已经走到头了,所以回过头来遍历2。
《图的遍历(python实现)》
整个遍历的顺序如下:
《图的遍历(python实现)》
使用深度优先遍历,查看图有多少个连通分量。

class ComponentsCounter(object):
    def __init__(self,aGraph):
        self.graph = aGraph
        self.result = 0 #store the number of component
        self.calc()

    def calc(self):
        for vertex in self.graph:
            vertex.setVisited(False) #let all the vertex being not visited
        for vertex in self.graph:
            if not vertex.getVisited(): #using dfs scan all the vertex that is not visited
                self._dfs(vertex,self.graph.getCCount())
                self.graph.setCCount(self.graph.getCCount() + 1)
                self.result += 1 #done,we need to plus 1

    def _dfs(self,startVertex,ccount):
        startVertex.setCCID(ccount) 
        #we can use id to check whether the two vertices was the same component or not.
        startVertex.setVisited(True)
        for nextVertex in startVertex.getConnections():
            if not nextVertex.getVisited():
                self._dfs(nextVertex,ccount)

    def getResult(self):
        return self.result
    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/qq_39422642/article/details/79519801
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞