views:

72

answers:

2

I am creating an algorithm that is based on directed graphs. I would like a function that will grab all the nodes that are attached to a particular node.

public List<Node> GetNodesInRange(Graph graph, int Range, Node selected)
{
    var result = new List<Node>();
    result.Add(selected);
    if (Range > 0)
    {
        foreach (Node neighbour in GetNeighbours(graph, selected))
        {
            result.AddRange(GetNodesInRange(graph, Range - 1, neighbour));
        }
    }
    return result;
}

private List<Node> GetNeighbours(Graph graph, Node selected)
{
    foreach(Node node in graph.node)
    {
        if (node == selected)
        {
            GetNodesInRange(node, Range-1, /*don't know what 2 do here*/);
            //and confused all the way down
+2  A: 

It depends on which kind of implementation you are using for your graph:

  • edge list: you search all edges that have the specified vertex as first or second parameter to the edge
  • adjacency list: the list attached to a node is already the list of nodes incident to it
  • adjacency matrix: you take the column (or row) of the vertex that you chose
Jack
A: 

You are calling GetNodesInRange inside GetNeighbours and GetNeighbours inside GetNodesInRange and that is creating problem.

Look at the answer by Jack.

And if you post how your Graph,Node and Edge looks like then we will be able to offer more help.

TheMachineCharmer