Neighborhood of Vertices

Topics: algorithm
Oct 31, 2010 at 9:41 PM
Edited Oct 31, 2010 at 10:31 PM

Hi,

I'm just getting started with the library and I'm trying to figure out how to use it "the right way". For example, I needed a function that returns the neighborhood of a vertex, much like this one:

http://igraph.sourceforge.net/doc/R/neighborhood.html

I was a bit surprised that such a function isn't already included, but it gave me a good chance to start learning the library. Here is what I came up with:

public static class NeighborhoodExtension
{
    private static void NeighborhoodHelper<TVertex, TEdge>(IVertexListGraph<TVertex, TEdge> graph, int order, TVertex vertex, EdgeFactory<TVertex, TEdge> edgeFactory, IMutableVertexAndEdgeListGraph<TVertex, TEdge> result)
        where TEdge : IEdge<TVertex>
    {
        if(result.AddVertex(vertex))
        {
            if (order > 0)
            {
                foreach (var edge in graph.OutEdges(vertex))
                {
                    NeighborhoodHelper(graph, order - 1, edge.Target, edgeFactory, result);
                    result.AddEdge(edgeFactory(vertex, edge.Target));
                }
            }
        }
    }

    public static IVertexAndEdgeListGraph<TVertex, TEdge> Neighborhood<TVertex, TEdge>(this IVertexListGraph<TVertex, TEdge> graph, int order, TVertex vertex, EdgeFactory<TVertex, TEdge> edgeFactory)
        where TEdge : IEdge<TVertex>
    {
        var result = new AdjacencyGraph<TVertex, TEdge>();

        NeighborhoodHelper(graph, order, vertex, edgeFactory, result);

        return result;
    }
}

It would be very helpful to receive some input by more experienced users. I'm sure there are many ways this code could be improved.

I'm looking forward to your comments!