Getting all edges going out from a node in jgrapht

6.3k views Asked by At

I am trying to randomly traverse through the graph in jgrapht (until I find some target node). To do it, I need to start at the sourceNode, randomly pick any coming out edge and follow it.

I know there there is a method getAllEdges(sourceVertex, targetVertex) that returns all the edges between two given nodes. But how can I get all edges while having only sourceNode, without the target one?

5

There are 5 answers

0
adarsh003 On BEST ANSWER

You can use Graphs.predecessorListOf and Graphs.successorListOf apis directly.

0
TheMP On

In case anyone wondered, I did not find any direct way to achieve this, so I went with Balkrishna suggestion from comments. My implementation (Java 8 style) is:

   private List<WeightedEdge> getAllEdgesFromNode(TransportGraph graph, MyNode startNode) {
    return graph.unwrap().edgeSet().stream()
            .filter(weightedEdge -> graph.unwrap().getEdgeSource(weightedEdge).equals(startNode))
            .collect(Collectors.toList());
}

Note: TransportGraph is a wrapper for jgrapht graph I have written myself. My method unwrap() returns SimpleDirectedWeightedGraph,

1
Juan On

I was trying to comment milez answer, but I mistakenly wrote it as an answer. So, let's write the answer. Milez proposed using JGrapht library, which I have used myself several times and works quite fine. This library has a RandomWalkIterator class which I think meets the requirements.

0
Memin On

You can access the outgoing edges of a node(vertex) with outgoingEdgesOf method of a graph object.

Set<MyEdge> edges = myGraph.outgoingEdgesOf(sourceNode);

Also, you can use incomingEdgesOf for the incoming edges.

If you want to access all edges of a node then use

graph.edgesOf(source)
0
milez On

Any object that implements the interface Graph<V,E> should have the method edgesOf(V vertex), at least according to the API. Your TransportGraph should be able to do this.