Hi I was wondering if there is any way to find all the possible paths between two nodes N1 and N2 in JUNG. Thanks in advance for any help :)
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
This simple solution returns all the paths.
It works also with cyclic graphs, printing all cycling paths, hence it can be used also for cycle detection, which is not available in JUNG.
It uses an arbitrary class
Entity
for the nodes, andEdge
for the edges. You can create such objects (make sure to implementhashcode()
andequals()
), or simply substitute them withString
objects, depending on your needs.I created a slight variation that allows you to use generics, but is no longer static. Your type has to be comparable though. For the basic method comparable is not necessary. However, I added another function, which was necessary for my purposes which was to find all unique paths, that is two paths cannot share an edge at the position in the path. I only check the same position of the paths for the same edge, so for example if both paths start with the same edge, they are not unique. If the i-th edge in both paths is shared it is not unique. The paths can still contain the same edge, just not in the same position (index) in the path. I also added a max-depth parameter, because it seems all paths is n! which is never good.
Here are some examples of unique-paths and the results for this implementation.
A--1-->B--2-->C and A--1-->D--2-->C = unique.
A--1-->B--2-->C--3-->D and A--1-->E--2-->C--3-->D = not unique. Edge C--3-->D is shared as edge 3.
A--1-->B--2-->C--3-->D and A--1-->E--2-->B--3-->C--4-->D = unique. Edge C--#--D is contained in both paths, however in the first path it is edge 3, and in the second path it is edge 4.
According to the documentation I don't think there is an out-of-the-box way to have all paths between two nodes. But you can easily adapt a breadth-first search to do this by managing a list of nodes that have been seen and visiting recursively the graph starting from the specified node. You can use the methods provided by the
AbstractGraph
class (doc here), eggetIncidentVertices
.In any case I don't think it is cheap problem..
Calculating all the possible paths between N1 and N2 costs O(n!) in the worst case, and may have that many outputs.
It is almost certainly the case that you don't want all the possible paths. What problem are you trying to solve?
I had some tasks in which i required all paths from vertex A to B.
Here, I took the ShortestPathDemo.java and modified it a bit to call it PathDemo.java. One can find both shortest and full path in a graph.