计算SCCs的Kosaraju算法

2024-09-28 01:30:12 发布

您现在位置:Python中文网/ 问答频道 /正文

对于给定的有向图G,我需要使用Kosaraju算法计算其强连通分量(SCC)。据我所知,算法的步骤如下:

  1. Grev=G所有弧反向
  2. Grev上运行DFS(深度优先搜索),以计算节点的完成时间
  3. G上运行DFS以发现SCC

我已设法找到所有节点的正确完成时间。我部分理解,我应该将完成时间分配给其各自的节点值,反转图形Grev,并在反转图形(现在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有什么关系

此外,我以迭代方式而不是递归方式执行此操作的原因是,分配的输入文件太大,程序将达到递归限制

编辑:回答问题后,我意识到问题与课程的荣誉代码不符。我对问题进行了编辑,以排除可能泄露作业解决方案的部分代码


Tags: ofthe代码infor节点stacktop
1条回答
网友
1楼 · 发布于 2024-09-28 01:30:12

因为我的问题只是:

What to do with the fin_times dictionary?

我将只提供该问题的解决方案,而不提供该作业的完整解决方案

因此答案似乎是颠倒fin_times字典,使键成为值,反之亦然:

order = dict((v, k) for k, v in finishing_times.items())

{1: 3, 2: 5, 3: 2, 4: 8, 5: 6, 6: 9, 7: 1, 8: 4, 9: 7}

然后,我们在G处理节点上按完成时间的降序运行DFS(在本例中,顶点7的完成时间为9)。与问题中的代码相对应,而不是:

for i in range(graph_elem - 1, 0, -1):
        stack.append(i)

我们写道:

order = dict((v, k) for k, v in finishing_times.items())

for i in range(graph_elem - 1, 0, -1):
        vertex = order[i]
        if vertex not in explored:
            stack.append(vertex)
            explored.add(vertex)

            // DFS code and SCC size computation...

相关问题 更多 >

    热门问题