如果您将图形存储为邻接列表,并且顶点由从1to的整数表示n-1,则不需要联合查找或哈希表。
让我们假设它g[v]是与 相邻的顶点列表(向量)v。此外,设cc为列表列表(向量的向量),其中cc[i]表示i-th连通分量中的顶点。为了实现的目的,让visited[v] = true当且仅当我们v在DFS例程中检查我们将使用。然后伪代码看起来像这样:
dfs(v, current_cc):
visited[v] = true
current_cc.append(v)
for u in g[v]:
if not visited[u]:
dfs(u, current_cc)
for v = 0 to n-1:
visited[i] = false
for v = 0 to n-1:
if not visited[v]:
current_cc = []
dfs(v, current_cc)
cc.append(current_cc)
//From now, cc[i] is a list of vertices in the i-th connected component,
//so we can easily iterate and call whatever we want on them.