Advertisement
cd62131

topological sort

May 28th, 2019
528
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. class Node:
  2.     def __init__(self, name):
  3.         self.name = name
  4.         self.nb = []
  5.         self.visited = False
  6.  
  7.     def __str__(self):
  8.         return self.name
  9.  
  10.  
  11. class Graph:
  12.     def __init__(self):
  13.         self.nodes = []
  14.         self.sorted = []
  15.  
  16.     def topological_sort(self):
  17.         self.sorted.clear()
  18.         for n in self.nodes:
  19.             self.__visit(n)
  20.  
  21.     def __visit(self, node):
  22.         if node.visited: return
  23.         node.visited = True
  24.         for n in node.nb:
  25.             self.__visit(n)
  26.         self.sorted.append(node)
  27.  
  28.  
  29. a = Node('A')
  30. b = Node('B')
  31. c = Node('C')
  32. d = Node('D')
  33. e = Node('E')
  34. f = Node('F')
  35. g = Node('G')
  36. h = Node('H')
  37. i = Node('I')
  38. j = Node('J')
  39.  
  40. a.nb[:] = [b, f]
  41. b.nb[:] = [h]
  42. d.nb[:] = [c, e, i]
  43. e.nb[:] = [i]
  44. g.nb[:] = [a, b, c]
  45. i.nb[:] = [c]
  46. j.nb[:] = [e]
  47.  
  48. G = Graph()
  49. G.nodes[:] = [a, b, c, d, e, f, g, h, i, j]
  50. G.topological_sort()
  51.  
  52. print([str(n) for n in reversed(G.sorted)])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement