1

I am given a list of edges (each of which have a 'From' and 'To' properties that specify which vertices they connect).

I want to either return a null if they don't form the cycle in this (undirected) graph, or return the list forming a cycle.

Does anyone know how I would go about such a problem? I am clueless.

2 Answers2

2

The way I've been taught to do this involves storing a list of visited vertices.

Navigate through the graph, storing each vertex and adding it to the list. Each turn, compare the current vertex to the list - if it is present, you've visited it before, and are therefore in a cycle.

Sean
  • 212
  • 1
  • 10
1

Algorithms of this type are called Graph Cycle Detection Algorithms. There are some intricacies about which algorithms to select based on the needs of the application or the context of the problem. For example, do you want to find the first cycle, the shortest cycle, longest cycle, all of the cycles, is the graph unidirectional or bidirectional, etc.?

There are numerous cycle detection algorithms to select from, depending on the need and the allowable computational complexity and the nature of the cycle (e.g. finding first, longest, etc.). Some common algorithms include the following:

  1. Floyd's Algorithm
  2. Brent's Algoritm (see also here)
  3. Tarjan's Strongly Connected Components Algorithm (see also this Stack Overflow post)

The specific algorithm you select will depend on your need and how efficient the algorithm must be. If serious efficiency is needed, I would suggest looking through some scholarly articles on the topic and compare and contrast some of the trade-offs of various algorithms.

Justin Albano
  • 3,809
  • 2
  • 24
  • 51