簡體   English   中英

Java中無向圖的邊緣

[英]Edge of undirected graph in Java

假設我正在編寫一個Java類來表示無向圖的邊緣。 這個類Edge包含兩個頂點tofrom

class Edge<Vertex> {

  private final Vertex to, from

  public Edge(Vertex to, Vertex from) {
    this.to = to;
    this.from = from;
  } 
  ... // getters, equals, hashCode ...
}

顯然e1 = new Edge(v1, v2)在無向圖中e1 = new Edge(v1, v2)e2 = new Edge(v2, v1)實際上是相同的。 是否有意義? 您將如何實現Edge類以滿足這一要求?

根據一些唯一的標識符對構造函數中的頂點執行排序。 這樣,無論順序如何,都可以一致地存儲它們。

我發現這比noMAD的解決方案更可取,因為與這些對象交互的所有代碼將對它們進行相同的對待,而不僅僅是您對equals的實現。

此外,調用類的成員tofrom是混亂,因為它聽起來像一個有向圖。 我將它們重命名為更通用的名稱,例如vertex1vertex2

  public Edge(Vertex x, Vertex y) {
      if (vertex2.getId() > vertex1.getId()) {
          this.vertex1 = x;
          this.vertex2 = y;
      } else {
          this.vertex1 = y;
          this.vertex2 = x;
      }
  } 

實際上,我的Edge類中不會包含這種邏輯,而是某種可監督的類,例如Graph類。 其原因是因為“ Edge只是具有兩個頂點的對象。 它對圖形的其余邊緣一無所知。

因此,為了擴展@noMad的答案,我實際上將他的checkIfSameEdge方法放在我的Graph類中:

public class Graph {
    private List<Edge> edges;
    ....
    public void addEdge(Edge e) {
        for (Edge edge : edges) {
            if (isSameEdge(edge, e) {
                return; // Edge already in Graph, nothing to do
        }
        edges.add(e);
    }
    private boolean isSameEdge(Edge edge1, Edge edge2) {
        return ((edge1.to.equals(edge2.to) && edge1.from.equals(edge2.from))
             || (edge1.to.equals(edge2.from) && edge1.from.equals(edge2.to)))
    }
}

BTW:我會重新命名tofromvertex1vertex2因為它是一個無向圖,並和指示方向,但是這只是我的opion。

好吧,在我的頭上,最幼稚的方法是:

protected boolean checkIfSameEdge(Vertex to, Vertex from) {
  if(to.equals(this.from) && from.equals(this.to) || to.equals(this.to) && from.equals(this.from)) {
    return true;
  return false;
}

顯然,您將必須重寫equalshashcode

假定節點包含某種標量值-根據這些值對參數進行排序(使用compareTo方法),並使用工廠創建新實例或返回現有實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM