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
//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
It returns the list of vertices conteined in the first path found.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 queue.add(source); marked.add(source); while(!queue.isEmpty()) { Vertex<String> u = queue.remove(); path.add(u); if(u.equals(destination)) { break; } for(Vertex<String> v : g.outVertices(u)) { if(!marked.contains(v)) { queue.add(v); marked.add(v); } } } return path; }
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?