Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
May 14th, 2012, 07:12 PM
 Alhazred
Registered User

Join Date: May 2012
Posts: 2
Time spent in forums: 24 m 2 sec
Reputation Power: 0
[Solved] All the paths between 2 nodes in a graph

I have a graph with not directed and which have cycles.
I need to find all the paths between 2 given nodes.

I've been able to write the code to find one path using BFS algorithm, but I can' modify it to make it return a list of all the paths.

This is my graph class
Code:
```//unuseful methods omitted to shorten the code
public class Graph<V,E> {

HashMap<Vertex<V>, List<Edge<V,E>>> graph;

public Graph() {
graph = new HashMap<Vertex<V>, List<Edge<V,E>>>();
}

/**
* @return true if 2 nodes are adjacent
*/
public boolean areAdjacent(Vertex<V> source, Vertex<V> destination)

/**
* @return all the edges in the graph
*/
public Collection<Edge<V,E>> edges()

/**
* @return edge between 2 vertices
*/
public Edge<V,E> getEdge(Vertex<V> source, Vertex<V> destination)

/**
* @return edges outgoing from source
*/
public Collection<Edge<V,E>> outEdges(Vertex<V> source)

/**

* @return vertices reachable from source
*/
public Collection<Vertex<V>> outVertices(Vertex<V> source)

/**
* @return all the vertices in the graph
*/
public Collection<Vertex<V>> vertices()
}```

This is the BFS function
Code:
```public static List<Vertex<String>> bfs(Graph<String,Integer> g, Vertex<String> source, Vertex<String> destination) {
Queue<Vertex<String>> queue = new ArrayDeque<Vertex<String>>();
HashSet<Vertex<String>> marked = new HashSet<Vertex<String>>();

List<Vertex<String>> path = new ArrayList<Vertex<String>>(); //will contain the vertices in the path found

while(!queue.isEmpty()) {
Vertex<String> u = queue.remove();

if(u.equals(destination)) { break; }

for(Vertex<String> v : g.outVertices(u)) {
if(!marked.contains(v)) {
}
}
}
return path;
}```

It returns the list of vertices conteined in the first path found.
How do I have to modify the BFS function to make it find all the paths between the 2 given vertices and return a list of all those paths?

#2
May 15th, 2012, 11:02 AM
 Alhazred
Registered User

Join Date: May 2012
Posts: 2
Time spent in forums: 24 m 2 sec
Reputation Power: 0
Problem solved.

 Viewing: Dev Shed Forums > Programming Languages > Java Help > All the paths between 2 nodes in a graph