1. 程式人生 > >圖的遍歷(python實現)

圖的遍歷(python實現)

深度優先遍歷

深度優先遍歷顧名思義就是一條路走到黑,如圖所示,從0開始遍歷,遍歷他的鄰邊1,當遍歷1時,發現他的鄰邊0已經遍歷了,所以這條路已經走到頭了,所以回過頭來遍歷2。
這裡寫圖片描述
整個遍歷的順序如下:
這裡寫圖片描述
使用深度優先遍歷,檢視圖有多少個連通分量。

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