nathanwailes

Topological sort

Apr 5th, 2024
709
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.79 KB | None | 0 0
  1. """
  2. Topological sorting for a directed graph is a linear ordering of its vertices such that for every directed edge UV from vertex U to vertex V, U comes before V in the ordering. Topological Sorting is possible if and only if the graph has no directed cycles, that is, if it is a Directed Acyclic Graph (DAG).
  3.  
  4. One common way to perform a topological sort is to use Kahn's Algorithm, which involves iteratively removing nodes with no incoming edges and removing their outgoing edges from the graph.
  5. """
  6. from collections import deque
  7.  
  8. def topological_sort(graph):
  9.     # Calculate in-degree (number of incoming edges) for each node
  10.     in_degree = {u: 0 for u in graph}  # Initialize in-degree as 0 for all vertices
  11.     for u in graph:
  12.         for v in graph[u]:
  13.             in_degree[v] += 1
  14.  
  15.     # Queue for all nodes with no incoming edge
  16.     queue = deque([u for u in graph if in_degree[u] == 0])
  17.    
  18.     top_order = []  # List to store the topological order
  19.  
  20.     while queue:
  21.         u = queue.popleft()  # Choose the vertex with no incoming edges
  22.         top_order.append(u)
  23.  
  24.         # Decrease in-degree by 1 for all its neighboring nodes
  25.         for v in graph[u]:
  26.             in_degree[v] -= 1
  27.             # If in-degree becomes zero, add it to the queue
  28.             if in_degree[v] == 0:
  29.                 queue.append(v)
  30.  
  31.     # Check if there was a cycle
  32.     if len(top_order) != len(graph):
  33.         return "The graph has at least one cycle and cannot be topologically sorted."
  34.     else:
  35.         return top_order
  36.  
  37. # Example usage
  38. graph = {
  39.     'A': ['B', 'C'],
  40.     'B': ['D', 'E'],
  41.     'C': ['F'],
  42.     'D': [],
  43.     'E': ['F'],
  44.     'F': []
  45. }
  46.  
  47. print(topological_sort(graph))
  48. # Output: ['A', 'B', 'C', 'D', 'E', 'F'] or any other order that satisfies the topological order conditions
Advertisement
Add Comment
Please, Sign In to add comment