// Single step of recursive DFS. private static void dfsRecursiveStep <TVertexId, TVertexProperty, TEdgeProperty>( this IGraph <TVertexId, TVertexProperty, TEdgeProperty> graph, IDfsStrategy <TVertexId> strategy, DfsRecursiveState <TVertexId> state) { Vertex <TVertexId> vertex = state.vertex; state.onEntry(vertex); strategy.OnEntry(vertex); foreach (Vertex <TVertexId> neighbour in graph.GetNeighbours(vertex)) { if (!state.reached.ContainsKey(neighbour)) { strategy.OnNextVertex(vertex, neighbour); state.vertex = neighbour; graph.dfsRecursiveStep(strategy, state); } else if (state.reached[neighbour] == state.iteration) { strategy.OnEdgeToVisited(vertex, neighbour); } } strategy.OnExit(vertex); state.onExit(vertex); }
/// <summary>Recursive deph-first-search algorithm.</summary> /// <param name="graph">a graph</param> /// <param name="strategy">a searching strategy</param> /// <param name="roots">starting vertices</param> /// <returns>enumerable of visited vertices</returns> public static IEnumerable <Vertex <TVertexId> > DfsRecursive <TVertexId, TVertexProperty, TEdgeProperty>( this IGraph <TVertexId, TVertexProperty, TEdgeProperty> graph, IDfsStrategy <TVertexId> strategy, IEnumerable <Vertex <TVertexId> > roots) { var state = new DfsRecursiveState <TVertexId>(); foreach (Vertex <TVertexId> root in roots) { if (!state.reached.ContainsKey(root)) { strategy.ForRoot(root); state.vertex = root; graph.dfsRecursiveStep(strategy, state); ++state.iteration; } } return(state.reached.Keys); }