簡體   English   中英

返回有向圖(jgrapht)中每個頂點的邊數

[英]Return number of edges of each vertex in a digraph (jgrapht)

我有使用以下方法創建的有向圖:

    public static DirectedGraph<Point, DefaultEdge> directedGraph = new DefaultDirectedGraph<Point, DefaultEdge>(DefaultEdge.class);

 void setup() { 

  Point myPoint = new Point(x, y);
  Point myNextPoint = new Point(xToFillNext, yToFillNext);
  directedGraph.addVertex(myPoint);
  directedGraph.addVertex(myNextPoint);
  directedGraph.addEdge(myPoint, myNextPoint);

  Point mySecondPoint = new Point(x, y);
  Point mySecondNextPoint = new Point(xToFillNext, yToFillNext);
  directedGraph.addVertex(mySecondPoint);
  directedGraph.addVertex(mySecondNextPoint);
  directedGraph.addEdge(mySecondPoint, mySecondNextPoint);

System.out.println("#vertices: "+ directedGraph.vertexSet());

}

 public static class Point {

  public int x;
  public int y;

  public  Point(int x, int y) 
  {

    this.x = x;
    this.y = y;
  }
  @Override
    public String toString() {
    return ("[x="+x+" y="+y+"]");
  }

  @Override
public int hashCode() {
    int hash = 7;
    hash = 71 * hash + this.x;
    hash = 71 * hash + this.y;
    return hash;
}



@Override
public boolean equals(Object other) 
{
    if (this == other)
       return true;

    if (!(other instanceof Point))
       return false;

    Point otherPoint = (Point) other;
    return otherPoint.x == x && otherPoint.y == y;
}
}

我想使用以下方法獲取每個頂點的向外邊緣數量:

directedGraph.outDegreeOf()

但是我不想逐個頂點地進行操作(這是一個簡單的代碼,可以更輕松地進行遍歷,在我的整個程序中,我有更多的頂點),我想遍歷頂點集並返回無論有多少個頂點,集合中每個頂點的向外邊緣的數量都會自動增加。

我應該如何進行呢?

(我使用基於Java的處理)

查看JGrapht API

DirectedGraph接口包含一個vertexSet()函數。 您可以使用它來迭代添加的頂點,並且可以獲得每個頂點的outDegreeValue()

for(Point p : directedGraph.vertexSet()){
   int degree = directedGraph.outDegreeOf(p);
   System.out.println("Degree of " p.toString() + ": " + degree);
}

我不確定DirectedGraph是否固有地存儲此信息,但是您可以通過使用hasmap在添加邊的同時輕松存儲此信息。

HashMap<Integer,Integer>  outEdgesMap = new HashMap<Integer,Integer>();

你在做

directedGraph.addEdge(myPoint, myNextPoint);

在這之后也做

outEdgesMap.put(myPoint,outEdgesMap.getOrDefault(myPoint,0)+1);

只是要清楚,它將是

directedGraph.addEdge(myPoint, myNextPoint);
outEdgesMap.put(myPoint,outEdgesMap.getOrDefault(myPoint,0)+1);

所以你的directedGraph.outDegreeOf()將是

        for(Integer i : outEdgesMap.keySet()){
             sout(i+ " : " +outEdgesMap.get(i) );
        }

暫無
暫無

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

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