对于给定的有向图G,我需要使用 Kosaraju 算法计算其强连通分量 (SCC)。据我了解,算法的步骤如下:
- 让G rev = G将所有弧反转
- 在G rev 上运行DFS(深度优先搜索)以计算节点的完成时间
- 在G上运行DFS以发现 SCC
我已经设法找到所有节点的正确完成时间。我部分理解我应该将完成时间分配给其各自的节点值,反转图G rev,然后在反转图(现在G )上再次运行 DFS,完成时间作为节点值处理节点,按完成时间的递减顺序. 我的理解正确吗?如果是这样,我该如何编码?
这是我到目前为止的地方:
# Number of elements in graph + 1
graph_elem = 10
def dfs_iterative(graph):
# variable initialization
for i in range(graph_elem - 1, 0, -1):
stack.append(i)
while stack:
v = ... # Get top of stack
# If the top of the stack is not explored, or if any of the children of
# the node on the top of the stack are unexplored, then continue the traversal
if ...:
#Mark explored
for head in graph[v]:
if head not in explored:
stack.append(head)
# Prevent the loop iterating through all of the children like BFS
else:
# Get finishing time for v
return finishing_times
# Graph represented in a list through edges
# index represents the tail node of the edge, and g[index] is the head node
# Example edges of g: (1, 4), (2, 8), (3, 6), etc.
g = [[], [4], [8], [6], [7], [2], [9], [1], [5, 6], [7, 3]]
rev_g = [[], [7], [5], [9], [1], [8], [3, 8], [4, 9], [2], [6]]
fin_times = dfs_iterative(rev_g)
fin_times
应该是{3: 1, 5: 2, 2: 3, 8: 4, 6: 5, 9: 6, 1: 7, 4: 8, 7: 9}
,并且如前所述,它是正确的。我现在与我有什么关系fin_times
?
此外,我迭代而不是递归地执行它的原因是分配的输入文件太大并且程序将达到递归限制。
编辑:在回答问题后,我意识到这个问题不符合课程的荣誉准则。我编辑了问题以排除可能会泄露分配解决方案的部分代码。