如何迭代图并列出所有连接 org.jgrapht

How to iterate Graph and list all connections with org.jgrapht

我正在尝试雇用

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

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

例如:-

"Team One" 有成员 "Team Member A"、"Team Member B"、"Team Member 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=团队顶点,分区 2= 玩家顶点}。

所以只需维护一个 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)));