返回有向图中每个顶点的边数(jgrapht)

时间:2015-07-29 17:44:37

标签: java processing jgrapht digraphs

我使用以下方法创建了有向图:

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

2 个答案:

答案 0 :(得分:1)

查看JGrapht API

DirectedGraph界面包含vertexSet()功能。您可以使用它来迭代您添加的顶点,并且每个顶点都可以得到outDegreeValue()

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

答案 1 :(得分: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) );
        }