4

I'm looking to make a graph that has vertices with some custom properties. For instance, have a vertex called "A" that also has x, y coordinates associated with it.

I've done this by creating a class that holds its identifier a string, and two ints. To get the class to play nicely with the AddEdge function I overrode .Equals and .GetHashCode so that and two vertices with the same identifier are equal and have the same hash code regardless of any other properties (like the coordinates)

This seems to work fine, I was able to run the built in DijkstraShortestPathAlgorithm successfully.

Question

My question is, is this the best way to go about it? It seems really inelegant. I end up writing really ugly lines like:

Edge<CustomVertex> a_e = new Edge<CustomVertex>(new CustomVertex("A"), new CustomVertex("E"));
graph.AddEdge(a_e);

Which I could easily make less ugly, but it just struck me that maybe what I'm doing is overkill.

I'm somewhat new to C#, and I've never used the QuickGraph (or Boost Graph) library before. I just want to attach simple properties to vertices. I was thinking I could also maintain a separate dictionary with the properties of each vertex, and leave the vertex class as a string instead of CustomVertex

Thoughts?

Full class:

class CustomVertex
{
    public String value { get; set; }

    public int x { get; set; }
    public int y { get; set; }

    public CustomVertex (String value){
        this.value = value;
        this.x = 0;
        this.y = 0;
    }

    public override bool Equals (object other)
    {
        if (other == null)
            return false;

        CustomVertex other_cast = other as CustomVertex;
        if ((System.Object)other_cast == null)
            return false;

        return this.value == other_cast.value;
    }

    public bool Equals(CustomVertex other)
    {
        if ((object)other == null)
            return false;

        return this.value == other.value;
    }

    public override int GetHashCode ()
    {
        return this.value.GetHashCode ();
    }

    public override string ToString ()
    {
        return this.value;
    }
}

And creating the graph looks like

AdjacencyGraph<CustomVertex, Edge<CustomVertex>> graph = new AdjacencyGraph<CustomVertex, Edge<CustomVertex>>(true);

graph.AddVertex(new CustomVertex("A"));
Joe Pinsonault
  • 537
  • 7
  • 16

0 Answers0