We have learned how to find the strong components for a directed graph in the class. Now, you are asked to implement the algorithm we discussed in the class. Given the adjacency lists of a di-graph, your function should print the affiliation of each node to the root of traversal tree it belongs to. For example, given the adjacency lists of the example below as [[3],[0],[0,3,4],[1],[2]]. We get two traversal trees after the second run of DFS: T1 = {(0,3), (3,1)}, T2 = {(2,4)}. Then, the nodes 0,1,3 all belong the tree rooted at node 0, and nodes 2, 4 belong to the tree rooted at node 2. You need to print an array [0, 0, 2, 0, 2]. You can use any python built-in package to complete this exercise.
时间: 2024-02-02 18:03:45 浏览: 101
Sure! Here's a Python implementation of the algorithm we discussed in class:
```python
def dfs(node, graph, visited, order):
visited[node] = True
for neighbor in graph[node]:
if not visited[neighbor]:
dfs(neighbor, graph, visited, order)
order.append(node)
def assign_affiliations(graph):
n = len(graph)
visited = [False] * n
order = []
for i in range(n):
if not visited[i]:
dfs(i, graph, visited, order)
transposed = [[] for _ in range(n)]
for i in range(n):
for neighbor in graph[i]:
transposed[neighbor].append(i)
visited = [False] * n
affiliations = [None] * n
for i in reversed(order):
if not visited[i]:
root = i
dfs(i, transposed, visited, affiliations)
for j in range(n):
if affiliations[j] is None:
affiliations[j] = root
return affiliations
```
To use this function with the example adjacency list you gave, you can simply call `assign_affiliations([[3],[0],[0,3,4],[1],[2]])`. This will return the desired output: `[0, 0, 2, 0, 2]`.
The basic idea of the algorithm is to first perform a depth-first search (DFS) on the graph and store the order in which nodes finish their recursive calls. We then transpose the graph (i.e., reverse all edges) and perform another DFS on the nodes in reverse order of the first DFS. For each node visited in this second DFS, we assign it to the same affiliation as its root, unless it has already been assigned an affiliation by a previous DFS call.
阅读全文