algorithm - 如果任何节点最多有 2 条边,则找出是否形成循环的更快方法?

标签 algorithm cycle

首先,没有作业。


问题是:

An undirected unweighted graph has N nodes.
Any node can have at most 2 edges to different nodes.
I need to know whether at least a cycle is formed.

输入:

M pairs of integers, as edges.
There can be duplicates, like "2 3" and "3 2".
The data may be invalid, for example: "1 2" "1 3" "1 4". The program needs to detect this.

我的方法(太慢):

0.1) A set for edges to detect duplicates. (C++ e.g.: std::set<int>)
0.2) A map for nodes to count how many edges from each node. (std::map<int,int>)
0.3) A list for links. A link is a set of connected nodes. (std::list<std::set<int> >)

1) Read in an edge, and change the edge to ascending order, e.g.: "3 2" -> "2 3".

2.1) If the edge has already be "drawn", skip and go to 1);
2.2) If either vertex has already got 2 edges, invalid! 
2.3) Otherwise, check whether either of the nodes has already been in a link.

3.1) If neither, create a new link and add to the list.
3.2) If only one, add the single one to the link.
3.3) If both,
3.3.1) If in the same link, a cycle has been formed!
3.3.2) If not, merge two links.

请推荐一个更快的算法,以及算法的数据结构。谢谢。

最佳答案

无向图的标准算法是简单地运行一个 depth first search在其上,跟踪当前路径上的节点。如果你遇到一个访问过的节点,那么你就有了一个循环。

关于algorithm - 如果任何节点最多有 2 条边,则找出是否形成循环的更快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6572511/

相关文章:

jquery - 添加 return true 到 jquery 循环的下一个/上一个按钮

c - C中奇怪的工作循环

arrays - 具有变量转换的多元回归自动化

algorithm - 具有交叉依赖性的最大流量减少

c++ - 从 std::string 中删除特定的连续字符重复

php - 如何找到邻近梅登黑德网格的定位器代码?

algorithm - 将图节点分布到桶中

python - 它是一种使用 itertools.cycle() 了解索引的方法吗?

jQuery Cycle - 同步随机化多个元素

arrays - 使用递归查找数组中的最大元素