Class DfsGraph<T>

java.lang.Object
com.thewinterframework.utils.graph.DfsGraph<T>
Type Parameters:
T - the type of nodes in the graph
All Implemented Interfaces:
Iterable<T>

public class DfsGraph<T> extends Object implements Iterable<T>
A simple directed graph implementation using Depth-First Search (DFS) for topological sorting. This class allows adding nodes and dependencies, and provides an ordered list of nodes based on their dependencies.
  • Constructor Details

    • DfsGraph

      public DfsGraph()
  • Method Details

    • addNode

      public void addNode(T node)
      Adds a node to the graph
      Parameters:
      node - the node to be added
    • addAfter

      public void addAfter(T after, T before)
      Adds a dependency indicating that 'after' should come after 'before'
      Parameters:
      after - - the node that comes after
      before - - the node that comes before
    • addBefore

      public void addBefore(T before, T after)
      Adds a dependency indicating that 'before' should come before 'after'
      Parameters:
      before - - the node that comes before
      after - - the node that comes after
    • ordered

      public List<T> ordered()
      Returns a list of nodes ordered based on their dependencies using DFS.
      Returns:
      a list of nodes in topological order
      Throws:
      IllegalStateException - if a cycle is detected in the graph
    • iterator

      @NotNull public @NotNull Iterator<T> iterator()
      Returns an iterator over the nodes in topological order.
      Specified by:
      iterator in interface Iterable<T>
      Returns:
      an iterator of nodes