Shields.Graphs/Graph.cs
/// <summary>
/// Performs a breadth-first traversal of a graph or digraph.
/// </summary>
/// <typeparam name="TNode">The type of a node.</typeparam>
/// <typeparam name="TKey">The type of a node key.</typeparam>
/// <param name="sources">The set of nodes from which to start the traversal.</param>
/// <param name="key">The function which maps a node to its key.</param>
/// <param name="next">The function which maps a node to its adjacent nodes.</param>
/// <param name="visited">The set of node keys which have already been visited. It will be updated during the method call.</param>
/// <returns>The breadth-first traversal of nodes.</returns>
Performs a breadth-first traversal of a graph or digraph.
Performs a breadth - first traversal of a graph or digraph .
private static IEnumerable<TNode> BreadthFirstTraversal<TNode, TKey>(
            IEnumerable<TNode> sources,
            Func<TNode, TKey> key,
            Func<TNode, IEnumerable<TNode>> next,
            HashSet<TKey> visited)
        {
            var queue = new Queue<TNode>(sources);
            while (queue.Any())
            {
                var u = queue.Dequeue();
                if (visited.Add(key(u)))
                {
                    yield return u;
                    foreach (var v in next(u))
                    {
                        if (!visited.Contains(key(v)))
                        {
                            queue.Enqueue(v);
                        }
                    }
                } 
            }
        }
private static IEnumerable < TNode > BreadthFirstTraversal < TNode , TKey > ( IEnumerable < TNode > sources , Func < TNode , TKey > key , Func < TNode , IEnumerable < TNode > > next , HashSet < TKey > visited ) { var queue = new Queue < TNode > ( sources ) ; while ( queue . Any ( ) ) { var u = queue . Dequeue ( ) ; if ( visited . Add ( key ( u ) ) ) { yield return u ; foreach ( var v in next ( u ) ) { if ( ! visited . Contains ( key ( v ) ) ) { queue . Enqueue ( v ) ; } } } } }
Performs a breadth-first traversal of a graph or digraph.
Performs a breadth - first traversal of a graph or digraph .
The breadth-first traversal of nodes.
The breadth - first traversal of nodes .
sources
IEnumerable<TNode>
The set of nodes from which to start the traversal.
The set of nodes from which to start the traversal .
key
Func<TNode, TKey>
The function which maps a node to its key.
The function which maps a node to its key .
next
Func<TNode, IEnumerable<TNode>>
The function which maps a node to its adjacent nodes.
The function which maps a node to its adjacent nodes .
visited
HashSet<TKey>
The set of node keys which have already been visited. It will be updated during the method call.
The set of node keys which have already been visited . It will be updated during the method call .
typeparam
The type of a node.
The type of a node .
typeparam
The type of a node key.
The type of a node key .