Given a directed adjacency matrix, return a topological sort of the nodes. order[i,j] = -1 means there is an edge from i to j. order[i,j] = 0 means there is no edge from i to j. order[i,j] = 1 means there is an edge from j to i. Args: order (np.array): The adjacency mat
(order: np.array)
| 9 | |
| 10 | @no_type_check |
| 11 | def topological_sort(order: np.array) -> List[int]: |
| 12 | """ |
| 13 | Given a directed adjacency matrix, return a topological sort of the nodes. |
| 14 | order[i,j] = -1 means there is an edge from i to j. |
| 15 | order[i,j] = 0 means there is no edge from i to j. |
| 16 | order[i,j] = 1 means there is an edge from j to i. |
| 17 | |
| 18 | Args: |
| 19 | order (np.array): The adjacency matrix. |
| 20 | |
| 21 | Returns: |
| 22 | List[int]: The topological sort of the nodes. |
| 23 | |
| 24 | """ |
| 25 | n = order.shape[0] |
| 26 | |
| 27 | # Calculate the in-degrees |
| 28 | in_degree = [0] * n |
| 29 | for i in range(n): |
| 30 | for j in range(n): |
| 31 | if order[i, j] == -1: |
| 32 | in_degree[j] += 1 |
| 33 | |
| 34 | # Initialize the queue with nodes of in-degree 0 |
| 35 | queue = [i for i in range(n) if in_degree[i] == 0] |
| 36 | result = [] |
| 37 | |
| 38 | while queue: |
| 39 | node = queue.pop(0) |
| 40 | result.append(node) |
| 41 | |
| 42 | for i in range(n): |
| 43 | if order[node, i] == -1: |
| 44 | in_degree[i] -= 1 |
| 45 | if in_degree[i] == 0: |
| 46 | queue.append(i) |
| 47 | |
| 48 | assert len(result) == n, "Cycle detected" |
| 49 | return result |
| 50 | |
| 51 | |
| 52 | @no_type_check |
no outgoing calls
no test coverage detected
searching dependent graphs…