从邻接表计算每个顶点的可达性

问题描述 投票:0回答:2

考虑到DAG的邻接表Map<Vertex, Set<Vertex>>,我想计算每个顶点的可达性(即,是否存在从u到v的路径)。

static Map<Vertex, Set<Vertex>> reachability(Map<Vertex, Set<Vertex>> adjList) {}

我知道可以在O(V^3)中使用Floyd-Warshall

// Convert adjList to adjacency matrix mat
void reachability(boolean mat[][]) {
  final int N = mat.length;
  for (int k = 0; k < N; k++)
    for (int i = 0; i < N; i++)
      for (int j = 0; j < N; j++)
        mat[i][j] |= mat[i][k] && mat[k][j];
}

但是我有一个稀疏图(和邻接表),所以最快的方法是什么?

algorithm graph-theory graph-algorithm floyd-warshall transitive-closure
2个回答
1
投票

O(V*(V+E))解决方案可能是对图中的每个节点进行简单的BFS并计算其可达性集。假设|E| << |V|^2(您说图表是稀疏的),这比floyd-warshall显着更快(并且更容易编写代码)。

但是,这仍然不是最理想的,可以改进:

您的图是DAG,因此您可以先在topological sort中执行O(V+E),然后从最后到第一个:

connected(v)=联合{connected(u)|对于所有边(v,u)} U {v}

这可以非常有效地计算,并为您提供时间复杂度O(|V|+|E|+k)的总答案,其中| V | -顶点数| E | -边数,k-连接对数(在最坏的情况下限制为O(|V|^2))。

此解决方案即使在没有稀疏图形的情况下也可以为您提供O(|V|^2)最差的性能。

伪代码:

V = [v0,v1,...,vn-1]
V = topological_sort(V) //O(V+E)
connect = new Map:V->2^V //Map<Vertex,Set<Vertex>> in java
i = n-1
while (i >= 0):
   let v be the vertex in V[i]
   connected[v].add(v)
   for each edge (v,u):
      //since the graph is DAG, and we process in reverse order
      //the value of connected[u] is already known, so we can use it.
      connected[v].addAll(connected[u])

0
投票

这是Scala中的一个简单的O(|V||E|)解决方案(基本上,对于每个顶点,都执行一个DFS:]

type AdjList[A] = Map[A, Set[A]]

def transitiveClosure[A](adjList: AdjList[A]): AdjList[A]  = {
  def dfs(seen: Set[A])(u: A): Set[A] = {
    require(!seen(u), s"Cycle detected with $u in it")
    (adjList(u) filterNot seen flatMap dfs(seen + u)) + u
  }
  adjList.keys map {u =>
    u -> dfs(Set.empty)(u)  
  } toMap
}

此处为可执行版本:http://scalafiddle.net/console/4f1730a9b124eea813b992edebc06840

© www.soinside.com 2019 - 2024. All rights reserved.