Advertisement
cd62131

topological sort

May 28th, 2019
554
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.80 KB | None | 0 0
  1. class Node:
  2.     def __init__(self, data):
  3.         self.data = data
  4.         self.neighbors = []
  5.         self.visited = False
  6.  
  7.     def add_neighbor(self, neighbor):
  8.         self.neighbors.append(neighbor)
  9.  
  10.     def set_visited(self, visited):
  11.         self.visited = visited
  12.  
  13.     def get_data(self):
  14.         return self.data
  15.  
  16.     def get_neighbors(self):
  17.         return self.neighbors
  18.  
  19.     def get_visited(self):
  20.         return self.visited
  21.  
  22.  
  23. class Graph:
  24.     def __init__(self):
  25.         self.nodes = []
  26.  
  27.     def add_node(self, node):
  28.         self.nodes.append(node)
  29.  
  30.     def topological_sort(self):
  31.         stack = []
  32.         for node in self.nodes:
  33.             self.recursive(node, stack)
  34.         for node in stack:
  35.             print(node.get_data())
  36.  
  37.     def recursive(self, node, stack):
  38.         if node.get_visited(): return
  39.         node.set_visited(True)
  40.         for nb in node.get_neighbors():
  41.             self.recursive(nb, stack)
  42.         stack.append(node)
  43.  
  44.  
  45. graph = Graph()
  46. node_A = Node('A')
  47. graph.add_node(node_A)
  48. node_B = Node('B')
  49. graph.add_node(node_B)
  50. node_C = Node('C')
  51. graph.add_node(node_C)
  52. node_D = Node('D')
  53. graph.add_node(node_D)
  54. node_E = Node('E')
  55. graph.add_node(node_E)
  56. node_F = Node('F')
  57. graph.add_node(node_F)
  58. node_G = Node('G')
  59. graph.add_node(node_G)
  60. node_H = Node('H')
  61. graph.add_node(node_H)
  62. node_I = Node('I')
  63. graph.add_node(node_I)
  64. node_J = Node('J')
  65. graph.add_node(node_J)
  66. node_A.add_neighbor(node_B)
  67. node_A.add_neighbor(node_F)
  68. node_B.add_neighbor(node_H)
  69. node_D.add_neighbor(node_C)
  70. node_D.add_neighbor(node_E)
  71. node_D.add_neighbor(node_I)
  72. node_E.add_neighbor(node_I)
  73. node_G.add_neighbor(node_A)
  74. node_G.add_neighbor(node_B)
  75. node_G.add_neighbor(node_C)
  76. node_I.add_neighbor(node_C)
  77. node_J.add_neighbor(node_E)
  78. graph.topological_sort()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement