|
1 | | -# Author: Phyllipe Bezerra (https://github.com/pmba) |
| 1 | +""" |
| 2 | +Graph topological sort implementation using Depth-First Search (DFS). |
2 | 3 |
|
3 | | -clothes = { |
4 | | - 0: "underwear", |
5 | | - 1: "pants", |
6 | | - 2: "belt", |
7 | | - 3: "suit", |
8 | | - 4: "shoe", |
9 | | - 5: "socks", |
10 | | - 6: "shirt", |
11 | | - 7: "tie", |
12 | | - 8: "watch", |
13 | | -} |
| 4 | +A topological sort or topological ordering of a directed graph is a linear |
| 5 | +ordering of its vertices in which each vertex comes before all vertices |
| 6 | +to which it has outgoing edges. |
14 | 7 |
|
15 | | -graph = [[1, 4], [2, 4], [3], [], [], [4], [2, 7], [3], []] |
| 8 | +For example, the graph representing clothing dependencies: |
| 9 | +- underwear -> pants -> belt -> suit |
| 10 | +- shirt -> tie -> suit |
| 11 | +- socks -> shoes |
16 | 12 |
|
17 | | -visited = [0 for x in range(len(graph))] |
18 | | -stack = [] |
| 13 | +Author: Phyllipe Bezerra (https://github.com/pmba) |
| 14 | +""" |
19 | 15 |
|
| 16 | +from collections.abc import Sequence |
20 | 17 |
|
21 | | -def print_stack(stack, clothes): |
22 | | - order = 1 |
23 | | - while stack: |
24 | | - current_clothing = stack.pop() |
25 | | - print(order, clothes[current_clothing]) |
26 | | - order += 1 |
27 | 18 |
|
| 19 | +class TopologicalSort: |
| 20 | + """Topological sort implementation using DFS.""" |
28 | 21 |
|
29 | | -def depth_first_search(u, visited, graph): |
30 | | - visited[u] = 1 |
31 | | - for v in graph[u]: |
32 | | - if not visited[v]: |
33 | | - depth_first_search(v, visited, graph) |
| 22 | + def __init__(self, graph: list[list[int]], labels: dict[int, str] | None = None) -> None: |
| 23 | + """Initialize the topological sorter. |
| 24 | +
|
| 25 | + Args: |
| 26 | + graph: Adjacency list representation where graph[u] contains |
| 27 | + all vertices v such that there is an edge from u to v. |
| 28 | + labels: Optional mapping from vertex indices to label strings |
| 29 | + for pretty printing results. |
| 30 | + """ |
| 31 | + self.graph = graph |
| 32 | + self.labels = labels or {} |
| 33 | + self.n = len(graph) |
| 34 | + self.visited: list[int] = [0] * self.n |
| 35 | + self.stack: list[int] = [] |
| 36 | + |
| 37 | + def _depth_first_search(self, u: int) -> None: |
| 38 | + """Perform DFS from vertex u, adding to stack after exploring all neighbors.""" |
| 39 | + self.visited[u] = 1 |
| 40 | + for v in self.graph[u]: |
| 41 | + if not self.visited[v]: |
| 42 | + self._depth_first_search(v) |
| 43 | + self.stack.append(u) |
| 44 | + |
| 45 | + def sort(self) -> list[int]: |
| 46 | + """Compute and return the topological ordering of vertices. |
| 47 | +
|
| 48 | + Returns: |
| 49 | + A list of vertices in topological order (each vertex appears before |
| 50 | + all vertices reachable from it). |
| 51 | + """ |
| 52 | + self.stack = [] |
| 53 | + self.visited = [0] * self.n |
| 54 | + |
| 55 | + for v in range(self.n): |
| 56 | + if not self.visited[v]: |
| 57 | + self._depth_first_search(v) |
| 58 | + |
| 59 | + return self.stack[::-1] |
| 60 | + |
| 61 | + def print_sorted(self, order: list[int]) -> None: |
| 62 | + """Print the vertices in topological order with their labels. |
| 63 | +
|
| 64 | + Args: |
| 65 | + order: A list of vertices in topological order. |
| 66 | + """ |
| 67 | + for i, vertex in enumerate(order, 1): |
| 68 | + label = self.labels.get(vertex, str(vertex)) |
| 69 | + print(f"{i}. {label}") |
34 | 70 |
|
35 | | - stack.append(u) |
36 | 71 |
|
| 72 | +def topological_sort(graph: list[list[int]], visited: list[int]) -> list[int]: |
| 73 | + """Topological sort of a directed acyclic graph using DFS. |
| 74 | +
|
| 75 | + Args: |
| 76 | + graph: Adjacency list representation of the graph. |
| 77 | + visited: List to track visited vertices (modified in place). |
| 78 | +
|
| 79 | + Returns: |
| 80 | + Vertices in topological order. |
| 81 | +
|
| 82 | + Examples: |
| 83 | + >>> graph = [[1, 2], [3], [3], []] |
| 84 | + >>> visited = [0] * len(graph) |
| 85 | + >>> topological_sort(graph, visited) |
| 86 | + [0, 2, 1, 3] |
| 87 | + """ |
| 88 | + stack = [] |
| 89 | + |
| 90 | + def dfs(u: int) -> None: |
| 91 | + visited[u] = 1 |
| 92 | + for v in graph[u]: |
| 93 | + if not visited[v]: |
| 94 | + dfs(v) |
| 95 | + stack.append(u) |
37 | 96 |
|
38 | | -def topological_sort(graph, visited): |
39 | 97 | for v in range(len(graph)): |
40 | 98 | if not visited[v]: |
41 | | - depth_first_search(v, visited, graph) |
| 99 | + dfs(v) |
| 100 | + |
| 101 | + return stack[::-1] |
42 | 102 |
|
43 | 103 |
|
44 | 104 | if __name__ == "__main__": |
45 | | - topological_sort(graph, visited) |
46 | | - print(stack) |
47 | | - print_stack(stack, clothes) |
| 105 | + # Example: Clothing dependencies |
| 106 | + clothes = { |
| 107 | + 0: "underwear", |
| 108 | + 1: "pants", |
| 109 | + 2: "belt", |
| 110 | + 3: "suit", |
| 111 | + 4: "shoe", |
| 112 | + 5: "socks", |
| 113 | + 6: "shirt", |
| 114 | + 7: "tie", |
| 115 | + 8: "watch", |
| 116 | + } |
| 117 | + |
| 118 | + graph = [[1, 4], [2, 4], [3], [], [], [4], [2, 7], [3], []] |
| 119 | + |
| 120 | + # Using the class-based interface |
| 121 | + sorter = TopologicalSort(graph, clothes) |
| 122 | + order = sorter.sort() |
| 123 | + sorter.print_sorted(order) |
| 124 | + |
| 125 | + # Also demonstrate the functional interface |
| 126 | + print("\n--- Using functional interface ---") |
| 127 | + visited = [0] * len(graph) |
| 128 | + result = topological_sort(graph, visited) |
| 129 | + print(result) |
0 commit comments