简体   繁体   中英

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.

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. So the output shall be [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. 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. 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.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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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