1

我有一个使用创建的有向图:

    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的处理)

4

2 回答 2

2

查看JGrapht API

DirectedGraph接口包含一个vertexSet()函数。您可以使用它来迭代您添加的顶点,并且可以获得outDegreeValue()每个顶点:

for(Point p : directedGraph.vertexSet()){
   int degree = directedGraph.outDegreeOf(p);
   System.out.println("Degree of " p.toString() + ": " + degree);
}
于 2015-07-29T17:59:41.353 回答
0

我不确定是否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) );
        }
于 2015-07-29T17:48:14.913 回答