我该如何搜索图的路径?我该、路径

2023-09-11 02:35:45 作者:陌上花开又花落

说我有边缘各包含两个节点(和从)的列表。什么是找边两个给定节点的最佳方法是什么?注意,在边缘节点可以重复

Say I have a list of edges each containing two nodes (to and from). What is the best way to find the edge two given nodes? Note that nodes in the edge may repeat.

说我有这种格式的优势:

Say I have edge in this format:

1< - > 5

1 <-> 5

3'; - > 7

3 <-> 7

5℃ - > 6

2'; - > 6

2<-> 6

然后查询,如1 5将返回真正

Then query such as 1 5 will return true.

然后查询,如5 2将返回真正,因为5连接6,6连接到2。

Then query such as 5 2 will return true because 5 connects 6 and 6 connects to 2.

然后查询等1 7将返回的错误

Then query such as 1 7 will return false.

然后查询,如7 4将返回的错误自从4犯规存在,这意味着它是边少节点。

Then query such as 7 4 will return false since 4 doesnt exist, it means it is edge-less node.

推荐答案

这听起来像你对我只是问,如果两个顶点之间存在无向图的路径,但不一定是这条道路可能。这是相同的,询问是否在两个顶点是在该图的同一连接的组件。

It sounds to me like you are just asking if a path exists between two vertices in an undirected graph, but not necessarily what that path might be. This is the same as asking if the two vertices are in the same connected component of the graph.

如果你真的只需要知道,如果两个顶点在同一个连通分量,再有就是使用的不相交集数据结构。

If you really do only need to know if the two vertices are in the same connected component, then there is a simple and efficient algorithm using a Disjoint-set data structure.

initialize the disjoint set structure (DSS)
for each edge:
  for each vertex in edge:
    if the vertex does not exist in the DSS:
      create a new subset in the DSS containing only the vertex
  merge the subsets of the two vertices

要确定是否处理所有的边缘后两个顶点之间存在一个路径,只检查是否两个顶点都在同一个子集。如果是这样,则它们之间存在一些路径

To determine if a path exists between two vertices after processing all the edges, just check if the two vertices are in the same subset. If they are, then some path exists between them.

通过一个高效的执行决策支持系统,该算法实现了比线性时间只是略差,甚至用一个简单的链接列表实现决策支持系统是为O(n * 的log(n))。为J _ 随机 _ 黑客提到,弗洛伊德,沃肖尔为O(n ^ 3)时间,为O(n ^ 2)存储不管,如果你只计算传递闭与否,并使用Dijkstra算法需要为O(n * 的log(n))为每个查询计算。

With an efficient implementation of the DSS, this algorithm achieves just slightly worse than linear time, and even with a simple linked-list implementation of the DSS it's O(n*log(n)). As j_random_hacker mentions, Floyd-Warshall is O(n^3) time and O(n^2) storage no matter if you are only calculating transitive closure or not, and using Dijkstra's algorithm requires an O(n*log(n)) calculation for each query.