Return 有向图中每个顶点的边数 (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()

但我不想逐个顶点地执行它(这是一个简单的代码,可以更容易地完成它,在我的整个程序中我有更多的顶点)并且我想完成顶点集和 return 集的每个顶点的向外边数自动,无论有多少顶点。

我应该如何进行此操作?

(我使用基于java的处理)

我不确定 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) );
        }

查看 JGrapht API

DirectedGraph interface contains a vertexSet()函数。您可以使用它来遍历您添加的顶点,并且可以获得每个顶点的 outDegreeValue()

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