3

我正在寻找一个具有一些自定义属性的顶点的图形。例如,有一个名为的顶点"A"也有x, y与之关联的坐标。

我通过创建一个包含其标识符 astring和 two的类来做到这一点ints。为了让该类与AddEdge我覆盖的函数很好地配合.Equals.GetHashCode因此具有相同标识符的两个顶点相等并且具有相同的哈希码,而不管任何其他属性(如坐标)

这似乎工作正常,我能够成功运行内置DijkstraShortestPathAlgorithm

问题

我的问题是,这是最好的方法吗?看起来真的很不雅。我最终写出了非常丑陋的线条,例如:

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

我可以很容易地让它变得不那么丑陋,但让我感到震惊的是,也许我正在做的事情有点矫枉过正。

我对 C# 有点陌生,而且我以前从未使用过 QuickGraph(或 Boost Graph)库。我只想将简单的属性附加到顶点。我在想我也可以使用每个顶点的属性维护一个单独的字典,并将顶点类保留为 astring而不是CustomVertex

想法?

全班:

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;
    }
}

创建图表看起来像

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

graph.AddVertex(new CustomVertex("A"));
4

0 回答 0