Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. def floyd_warshall(n, edge):
  2. rn = range(n)
  3. dist = [[inf] * n for i in rn]
  4. nxt = [[0] * n for i in rn]
  5.  
  6. for i in rn:
  7. for j in rn:
  8. nxt[i][j]=[-1]
  9.  
  10. for i in rn:
  11. dist[i][i] = 0
  12.  
  13. for u, v, w in edge:
  14. dist[u][v] = w
  15. nxt[u][v]=[v]
  16.  
  17. for k in rn:
  18. for i in rn:
  19. for j in rn:
  20. sum_ik_kj = dist[i][k] + dist[k][j]
  21. if dist[i][j] > sum_ik_kj:
  22. dist[i][j] = sum_ik_kj
  23. nxt[i][j]=nxt[i][k]
  24.  
  25. elif(sum_ik_kj==dist[i][j] and dist[i][j]!=inf and k!=j and k!=i):
  26. nxt[i][j].extend(nxt[i][k])
  27.  
  28. return nxt
  29.  
  30. edge = [[0,2,2],[2,3,2],[3,1,1],[1,0,4],[1,2,3],[0,3,4],[3,0,5]]
  31. # Here n is the value of the highest numbered-vertex. In the above graph, n=4
  32. n=4
  33. nxt=floyd_warshall(n,edge)
  34.  
  35. for i in range(n):
  36. for j in range(n):
  37. if(i!=j):
  38. allPaths=[]
  39. allPaths=getpath(i,j,next,allPaths)
  40. print(allPaths)
  41.  
  42. def getpath(i,j,nxt,allPaths):
  43. for k in next[i][j]:
  44. if(k==-1):
  45. allPaths.extend([i,j])
  46.  
  47. elif(k==j):
  48. allPaths.append(j)
  49.  
  50. else:
  51. paths_I_K=getpath(i,k,next,allPaths)
  52. paths_K_J=getpath(k,j,next,allPaths)
  53. for i_k in paths_I_K:
  54. for k_j in paths_K_J:
  55. i_k.pop()
  56. allPaths.append(i_k+k_j)
  57. return allPaths
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement