Advertisement
Guest User

Untitled

a guest
Mar 27th, 2017
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.17 KB | None | 0 0
  1. class Vertice:
  2. def __init__(self,n):
  3. self.nombre = n
  4. self.vecinos = list()
  5.  
  6. self.d = 0
  7. self.f = 0
  8. self.color = 'white'
  9. self.pred = -1
  10.  
  11. def agregarVecino(self, v):
  12. if v not in self.vecinos:
  13. self.vecinos.append(v)
  14. self.vecinos.sort()
  15. class Grafo:
  16. vertices = {}
  17. tiempo = 0
  18.  
  19. def agregarVertice(self, vertice):
  20. if isinstance(vertice, Vertice) and vertice.nombre not in self.vertices:
  21. self.vertices[vertice.nombre] = vertice
  22. return True
  23. else:
  24. return False
  25.  
  26. def agregarArista(self, u, v):
  27. if u in self.vertices and v in self.vertices:
  28. for key, value in self.vertices.items():
  29. if key == u:
  30. value.agregarVecino(v)
  31. #if key == v: #Se comenta porque es grafo dirigido
  32. # value.agregarVecino(u)
  33. return True
  34. else:
  35. return False
  36.  
  37. def imprimeGrafo(self):
  38. for key in sorted(list(self.vertices.keys())):
  39. print("Vertice: "+key )
  40. print("Descubierto/termino: "+str(self.vertices[key].d)+ "/"+ str(self.vertices[key].f))
  41.  
  42. def dfs(self, vert):
  43. global tiempo
  44. tiempo = 0
  45. for v in sorted(list (self.vertices.keys())):
  46. if self.vertices[v].color == 'white':
  47. self.dfsVisitar (self.vertices[v])
  48.  
  49. def dfsVisitar(self, vert):
  50. global tiempo
  51. tiempo = tiempo + 1
  52. vert.d = tiempo
  53. vert.color = 'gris'
  54.  
  55. for v in vert.vecinos:
  56. if self.vertices[v].color == 'white':
  57. self.vertices[v].pred = vert
  58. self.dfsVisitar(self.vertices[v])
  59. vert.color = 'black'
  60. tiempo = tiempo + 1
  61. vert.f = tiempo
  62.  
  63. class Controladora:
  64. def main(self):
  65. g = Grafo()
  66. a = Vertice('U')
  67. g.agregarVertice(a)
  68.  
  69. for i in range(ord('U'), ord('[')):
  70. g.agregarVertice(Vertice(chr(i)))
  71.  
  72. edges = ['UV','UX','VY','YX','XV','WY','WZ']
  73. for edge in edges:
  74. g.agregarArista(edge[:1], edge[1:])
  75. g.dfs(a)
  76. g.imprimeGrafo()
  77.  
  78. obj = Controladora()
  79. obj.main()
  80.  
  81. Vertice: U
  82. Descubierto/termino: 1/8
  83. Vertice: V
  84. Descubierto/termino: 2/7
  85. Vertice: W
  86. Descubierto/termino: 9/12
  87. Vertice: X
  88. Descubierto/termino: 4/5
  89. Vertice: Y
  90. Descubierto/termino: 3/6
  91. Vertice: Z
  92. Descubierto/termino: 10/11
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement