PYTHON实现DFS算法

 1 class Vertice:
 2   def __init__(self,index):
 3     self.no = index
 4     self.color = 0 # 0:white 1 gray 2 black
 5     self.vt = 0
 6   def getNextV(self):
 7     return self.nextV
 8   def setNextV(self,*nextVertice):
 9       self.nextV = nextVertice
10   def setColor(self,color):
11     self.color = color
12   def getColor(self):
13     return self.color
14   def incVt(self):
15     self.vt += 1
16   def getVt(self):
17     return self.vt
18 
19 v1 = Vertice(1)
20 v2 = Vertice(2)
21 v3 = Vertice(3)
22 v4 = Vertice(4)
23 v5 = Vertice(5)
24 
25 v1.setNextV(v2,v5)
26 v2.setNextV(v1,v5,v4,v3)
27 v3.setNextV(v2,v4)
28 v4.setNextV(v2,v3,v5)
29 v5.setNextV(v1,v2,v4)
30 
31 v100 = Vertice(100)
32 v100.setNextV(v1,v2,v3,v4,v5)
33 
34 def DFS_Visit(v):
35   v.setColor(1)
36   v.incVt()
37   for it in v.getNextV():
38     if it.getColor() == 0:
39         DFS_Visit(it)
40   v.setColor(2)
41   
42 DFS_Visit(v100)
43 
44 for it in v100.getNextV():
45     print it.getVt()
46   

 

    原文作者:兵形东华
    原文地址: https://www.cnblogs.com/donghua/p/6804301.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞