gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:02:18 30 4
gpt4 key购买 nike

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

    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);
}

关于java - 返回有向图中每个顶点的边数 (jgrapht),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31707538/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com