Advertisement
Guest User

Bellman-Ford

a guest
Nov 14th, 2019
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. import heapq as hq
  2. import math
  3. from random import *
  4. import networkx as nx
  5. INF = float("inf")
  6.  
  7. def generarGrafoConPesos(n,m):
  8. mat = [[] for i in range(n)]
  9. for j in range(m):
  10. v1 = randint(0, n - 1)
  11. v2 = randint(0, n - 1)
  12. w = randint(1, 10)
  13. adyacentes = [x[0] for x in mat[v1]]
  14. adyacentes2 = [x[0] for x in mat[v2]]
  15. while(v2 in adyacentes or v2 == v1 or v1 in adyacentes2):
  16. v1 = randint(0, n - 1)
  17. v2 = randint(0, n - 1)
  18. mat[v1] += [(v2,w)]
  19. return mat
  20.  
  21. def dibujarGrafoConPesos(lista):
  22. G = nx.DiGraph()
  23. for i in range(len(g)):
  24. G.add_node(i)
  25. for v1 in range(len(lista)):
  26. for v2 in lista[v1]:
  27. G.add_edge(v1, v2[0],weight=v2[1])
  28. nx.draw_circular(G, with_labels=True, font_weight='bold', node_size=500)
  29. labels = nx.get_edge_attributes(G,'weight')
  30. nx.draw_networkx_edge_labels(G,pos=nx.circular_layout(G),edge_labels=labels)
  31. g = generarGrafoConPesos(10,28)
  32.  
  33. print(g)
  34. dibujarGrafoConPesos(g)
  35.  
  36. def BellmanFord(g, inicio):
  37. distancia = [INF] * len(g)
  38. predecesor = [(-1,-1)] * len(g)
  39.  
  40. distancia[inicio] = 0
  41. for i in range(len(g) - 1):
  42. for u in range(len(g)):
  43. for v,w in g[u]:
  44. if distancia[u] != INF and distancia[u] + w < distancia[v]:
  45. distancia[v] = distancia[u] + w
  46. predecesor[v] = (u,w)
  47. return distancia, predecesor
  48.  
  49. BellmanFord(g, 0)
  50.  
  51. def hacerRecorridosBellmanFord(g,inicio):
  52. d, p = BellmanFord(g, inicio)
  53. recorrido = []
  54. for u in range(len(p)):
  55. if p[u][0] > -1:
  56. recorrido += [(p[u][0],u,p[u][1])]
  57. return recorrido
  58.  
  59. hacerRecorridosBellmanFord(g,0)
  60.  
  61. #opcional
  62. def dibujarRecorrido(g,recorrido):
  63. G = nx.DiGraph()
  64. for i in range(len(g)):
  65. G.add_node(i)
  66. for x in recorrido:
  67. G.add_edge(x[0], x[1], weight = x[2])
  68. nx.draw_circular(G, with_labels=True, font_weight='bold', node_size=500)
  69. labels = nx.get_edge_attributes(G,'weight')
  70. nx.draw_networkx_edge_labels(G,pos=nx.circular_layout(G),label_pos=0.3,edge_labels=labels)
  71.  
  72. dibujarRecorrido(g, hacerRecorridosBellmanFord(g,0))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement