|
| 1 | +'''Purpose: Orders vertices of a Directed Acyclic Graph (DAG) such that for every directed edge u → v, vertex u comes before v in the ordering. |
| 2 | +
|
| 3 | +Type: Graph Algorithm |
| 4 | +
|
| 5 | +Use Cases: Task scheduling, course prerequisite ordering, build systems, etc. |
| 6 | +
|
| 7 | +Approach: We can implement Toposort using DFS: |
| 8 | +
|
| 9 | +For each unvisited node, perform a DFS. |
| 10 | +
|
| 11 | +After visiting all neighbors, push the node to a stack. |
| 12 | +
|
| 13 | +At the end, pop nodes from the stack to get the topological order. |
| 14 | +
|
| 15 | +Time Complexity: O(V + E) |
| 16 | +
|
| 17 | +Space Complexity: O(V)''' |
| 18 | + |
| 19 | +# Topological Sorting using DFS in Python |
| 20 | + |
| 21 | +from collections import defaultdict |
| 22 | + |
| 23 | +class Graph: |
| 24 | + def __init__(self, vertices): |
| 25 | + self.V = vertices |
| 26 | + self.graph = defaultdict(list) |
| 27 | + |
| 28 | + # Add an edge from u to v |
| 29 | + def add_edge(self, u, v): |
| 30 | + self.graph[u].append(v) |
| 31 | + |
| 32 | + # Recursive helper function for DFS |
| 33 | + def _dfs(self, v, visited, stack): |
| 34 | + visited[v] = True |
| 35 | + for neighbor in self.graph[v]: |
| 36 | + if not visited[neighbor]: |
| 37 | + self._dfs(neighbor, visited, stack) |
| 38 | + stack.append(v) # Push vertex after visiting neighbors |
| 39 | + |
| 40 | + # Topological Sort |
| 41 | + def topological_sort(self): |
| 42 | + visited = [False] * self.V |
| 43 | + stack = [] |
| 44 | + |
| 45 | + for i in range(self.V): |
| 46 | + if not visited[i]: |
| 47 | + self._dfs(i, visited, stack) |
| 48 | + |
| 49 | + # Return in reverse order |
| 50 | + return stack[::-1] |
| 51 | + |
| 52 | +# Main function |
| 53 | +if __name__ == "__main__": |
| 54 | + # Example graph |
| 55 | + g = Graph(6) |
| 56 | + g.add_edge(5, 2) |
| 57 | + g.add_edge(5, 0) |
| 58 | + g.add_edge(4, 0) |
| 59 | + g.add_edge(4, 1) |
| 60 | + g.add_edge(2, 3) |
| 61 | + g.add_edge(3, 1) |
| 62 | + |
| 63 | + print("Topological Sort of the given graph:") |
| 64 | + order = g.topological_sort() |
| 65 | + print(order) |
0 commit comments