如何迭代Graph并列出与org.jgrapht的所有连接

时间:2018-04-19 15:59:35

标签: java graph-traversal jgrapht jgraph

我正在尝试使用

compile group: 'org.jgrapht', name: 'jgrapht-core', version: '1.1.0'

可视化团队与团队成员之间的关系。

例如: -

“Team One”的成员为“团队成员A”,“团队成员B”,“团队成员C”

“Team Two”的成员为“Team Member C”,“Team Member D”

所以我添加了以下顶点

final Graph<Displayable, DefaultEdge> directedGraph = new DefaultDirectedGraph<>(DefaultEdge.class);

directedGraph.addVertex(team_0001);
directedGraph.addVertex(team_0002);
directedGraph.addVertex(teamMember_A);
directedGraph.addVertex(teamMember_B);
directedGraph.addVertex(teamMember_C);
directedGraph.addVertex(teamMember_D);

directedGraph.addEdge(team_0001, teamMember_A);
directedGraph.addEdge(team_0001, teamMember_B);
directedGraph.addEdge(team_0001, teamMember_C);
directedGraph.addEdge(team_0002, teamMember_C);
directedGraph.addEdge(team_0002, teamMember_D);

当我遍历此图时,我想要以下输出: -

Team_0001
  teamMember_A
  teamMember_B
  teamMember_C

Team_0002
  teamMember_C
  teamMember_D

我怎样才能做到这一点?

我是否必须开发客户图形迭代器?

1 个答案:

答案 0 :(得分:2)

根据定义,您的图表是二分的:{Partition 1 = Team vertices,Partition 2 = player vertices}。

所以只需维护一个Team顶点列表,并为每个顶点调用Graphs.neighborListOf(.)

List<Displayable> teams=...; for(Displayable v : teams) System.out.println("Team"+v+" has the following members: "+Graphs.neighborListOf(teamGraph,v);

或者,由于您的图表是定向的,您可以迭代边缘:

for(DefaultEdge e : teamGraph.edgeSet()) System.out.println(String.format("Player %s belongs to team %s",teamGraph.getEdgeTarget(e), teamGraph.getEdgeSource(e)));