This clearly can be viewed as a problem in graph theory. There is a good chance a solution can be found on CPAN. Even if you fail to find such module, the time spent looking is probably not wasted because you will learn standard terminology and learn not to wast time on promising approaches that do not work.