findCycle method

List<Vertex<T>> findCycle()

Returns the first cycle detected or an empty list if the graph is acyclic. In general, the getter method cycle is faster, but findCycle() is efficient if the graph is sparcely connected.

Note: A cycle is a path that starts and ends with the same vertex.

Implementation

List<Vertex<T>> findCycle() {
  final crawler = GraphCrawler<T>(edges: edges);
  List<List<Vertex<T>>> cycles;

  // Main loop
  for (final vertex in vertices) {
    if (_inDegreeMap[vertex] == 0) continue;
    if (outDegree(vertex) == 0) continue;
    cycles = crawler.fastPaths(vertex, vertex, stopEarly: true);

    if (cycles.isNotEmpty) return cycles.first;
  }
  return [];
}