Search code examples
c#algorithmdata-structuresa-star

How do I create a graph from this datastructure?


I took this data structure from this A* tutorial:

public interface IHasNeighbours<N>
{
    IEnumerable<N> Neighbours { get; }
}

public class Path<TNode> : IEnumerable<TNode>
{
    public TNode LastStep { get; private set; }
    public Path<TNode> PreviousSteps { get; private set; }
    public double TotalCost { get; private set; }
    private Path(TNode lastStep, Path<TNode> previousSteps, double totalCost)
    {
        LastStep = lastStep;
        PreviousSteps = previousSteps;
        TotalCost = totalCost;
    }
    public Path(TNode start) : this(start, null, 0) { }
    public Path<TNode> AddStep(TNode step, double stepCost)
    {
        return new Path<TNode>(step, this, TotalCost + stepCost);
    }
    public IEnumerator<TNode> GetEnumerator()
    {
        for (Path<TNode> p = this; p != null; p = p.PreviousSteps)
            yield return p.LastStep;
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }

}

I have no idea how to create a simple graph with.

How do I add something like the following undirected graph using C#:

alt text

Basically I'd like to know how to connect nodes. I have my own datastructures that I can already determine the neighbors and the distance. I'd now like to convert that into this posted datastructure so I can run it through the AStar algorithm.

I was seeking something more like:

 Path<EdgeNode> startGraphNode = new Path<EdgeNode>(tempStartNode);
 startGraphNode.AddNeighbor(someOtherNode, distance);

Solution

  • This is because you use the wrong structure to represent the graph. The A* (and the path here) are used to find a path between two nodes within a graph. A Path is inherently directional and can be flatten to a single line. For example, in your graph above the only possible path that would go through all Nodes starts at 3 and ends at 2 (note that the latter would be added twice in your path, weather or not this makes sense depends largely on the problem you are trying to solve.

    So basically you first need a representation for the graph, then from it you can run algorithm though them to solve particular problems.

    The most basic form of graph is basically a node with a member list of neighbouring nodes. Then you can try A* on it. Designate a starting node and an end node and find a path between them