imashutosh51

Topological Sort using BFS(Kahn's algorithm)

Mar 22nd, 2026 (edited)
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.87 KB | None | 0 0
  1. """
  2. Intuition for Kahn's Algorithm (BFS-based Topological Sort)
  3.  
  4. Step 1: Identify the Problem Type
  5. ---------------------------------
  6. Topological Sort is a linear ordering of vertices such that for every
  7. directed edge u -> v, node u comes before v. This is only possible in
  8. a Directed Acyclic Graph (DAG). Since we want to solve this using BFS
  9. (level-by-level processing), we use Kahn's Algorithm.
  10.  
  11. Step 2: The Core Concept (In-Degree)
  12. ------------------------------------
  13. In BFS, we usually start from a 'source'. In a DAG, a logical starting
  14. point is a node that has NO dependencies.
  15. - In-Degree: The number of incoming edges to a node.
  16. - If In-Degree == 0: No other node needs to come before this one.
  17.  It can safely be placed at the beginning of our ordering.
  18.  
  19. Step 3: Initializing the Process
  20. --------------------------------
  21. 1. Calculate the In-Degree of all nodes by traversing the adjacency list.
  22. 2. Find all nodes with In-Degree 0 and push them into a Queue.
  23.   - These are our 'starting' nodes.
  24.  
  25. Step 4: The 'Removal' Logic (The BFS Loop)
  26. ------------------------------------------
  27. While the Queue is not empty:
  28. 1. Pop a node 'u' from the Queue and add it to the Topological Sort result.
  29. 2. For every adjacent node 'v' (where an edge u -> v exists):
  30.   - 'Virtually' remove the edge u -> v.
  31.   - Since node 'u' is now placed in the ordering, node 'v' has one
  32.     fewer dependency.
  33.   - Decrease the In-Degree of node 'v' by 1.
  34.  
  35. Step 5: Activating New Nodes
  36. ----------------------------
  37. After decreasing the In-Degree of node 'v', check:
  38. - If In-Degree of 'v' becomes 0: All its dependencies have been placed
  39.  in the ordering.
  40. - Push node 'v' into the Queue so it can be processed next.
  41.  
  42. Step 6: Final Result
  43. --------------------
  44. Once the Queue is empty, the nodes in our result list are in
  45. Topological Order.
  46. - Note: If the result list contains fewer than 'V' nodes, the graph
  47.  must have a cycle (Topological Sort is impossible).
  48.  
  49. Step 7: Complexity
  50. ------------------
  51. - Time: O(V + E) - We visit every node and every edge once.
  52. - Space: O(V) - To store the In-Degrees and the Queue.
  53. """
  54. from collections import defaultdict
  55. class Solution:
  56.     def topoSort(self, v, edges):
  57.         adj=defaultdict(list)
  58.         indegree=[0]*v
  59.         for a,b in edges:
  60.             adj[a].append(b)
  61.             indegree[b]+=1
  62.         st=[]
  63.         for i in range(v):
  64.             if indegree[i]==0:
  65.                 st.append(i)
  66.        
  67.         ans=[]
  68.         while st: #visited is not needed here because once the indegree of a node is 0 and you again go to that node, it will make it -1
  69.             temp=st.pop()
  70.             ans.append(temp)
  71.             for neigh in adj[temp]:
  72.                 indegree[neigh]-=1
  73.                 if indegree[neigh]==0:
  74.                     st.append(neigh)
  75.         return ans
  76.                
  77.        
  78.            
  79.        
Advertisement
Add Comment
Please, Sign In to add comment