简体   繁体   English

给定行的循环检测

[英]Loop Detection with given lines

I'd like to detect a "complete loop".我想检测一个“完整的循环”。 Let's suppose that lists are connectable if the first value of a list is equal to the end value of another list.假设如果列表的第一个值等于另一个列表的结束值,则列表是可连接的。 For example, we may have 5 lists like below.例如,我们可能有 5 个如下列表。

a1 = [1, 14, 0]
a2 = [2, 14, 3]
a3 = [0, 14, 2]
a4 = [3, 14, 1]
a5 = [0, 14, 3]

where a1, a3, a2, and a4 can be connected to each other, forming a "complete loop" as a4 and a1 can also be connected.其中 a1、a3、a2 和 a4 可以相互连接,形成一个“完整的回路”,因为 a4 和 a1 也可以连接。 So the output shall be [a1, a3, a2, a4].所以 output 应该是 [a1, a3, a2, a4]。

(It looked like as if it were an NP-Hard Problem, but I think I was wrong,) I've tried solutions such as Doubly Linked List or Hash Table, but it somehow then turned out to be recursive programming. (看起来好像是一个 NP-Hard 问题,但我认为我错了,)我尝试了诸如双链表或 Hash 表之类的解决方案,但后来不知何故变成了递归编程。 which I'm terrible at and was not very successful.我很糟糕,而且不是很成功。

Of course, I may just generate all the permutations and check one by one.当然,我可能只是生成所有排列并一一检查。 Can there be a more beautiful way?有没有更美的方式?

This is not NP-hard.这不是 NP 难的。 Conceptually, this problem is known as 'cycle detection' and is a part of graph theory.从概念上讲,这个问题被称为“循环检测”,是图论的一部分。

If you would like to see the code approaches to cycle detection, here is a decent beginner's tutorial:如果您想查看循环检测的代码方法,这里有一个不错的初学者教程:

https://www.tutorialspoint.com/Detect-Cycle-in-a-an-Undirected-Graph https://www.tutorialspoint.com/Detect-Cycle-in-a-an-Undirected-Graph

https://www.techiedelight.com/check-undirected-graph-contains-cycle-not https://www.techiedelight.com/check-undirected-graph-contains-cycle-not

If this problem was NP-hard, we wouldn't be able to do a lot of relatively-important things like dependency calculations and circular reference detection.如果这个问题是 NP-hard,我们将无法做很多相对重要的事情,比如依赖计算和循环引用检测。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM