Been trying to build a method that gets all conceivable unique paths through a DAG. Went with recursion because it seemed like the easiest to understand. Ended up with this:
public class Brutus { //the previous nodes visited public ArrayList<Node> resultHistory = new ArrayList<Node>(); //Directed Graph class, contains a HashMap [adjacencies] // that has keys for all nodes that contains all edges public AdjacencyList paths; //A list of all the pathways between nodes represented as a list of nodes public ArrayList<ArrayList<Node>> allPaths = new ArrayList<ArrayList<Node>>(); public Brutus(AdjacencyList paths) { this.paths = paths; } public ArrayList<ArrayList<Node>> findAll() { int counter = 1; for (Node key : paths.adjacencies.keySet()) { System.out.println("[" + counter + "]: " + key.toString()); StringTokenizer st = new StringTokenizer( paths.getAdjacentString(key), ","); while (st.hasMoreTokens()) { String child = st.nextToken(); if (paths.getNodeFromGraph(child) != null) { resultHistory = new ArrayList<Node>(); resultHistory.add(key); findPath(child, resultHistory); } } counter++; } return allPaths; } public void findPath(String child, ArrayList<Node> resultHistory) { if (resultHistory.contains(paths.getNodeFromGraph(child))) { return; } resultHistory.add(paths.getNodeFromGraph(child)); if(!(inList(resultHistory, allPaths))) { allPaths.add(resultHistory); } StringTokenizer st = new StringTokenizer( paths.getAdjacentString(paths.getNodeFromGraph(child)), ","); while (st.hasMoreTokens()) { child = st.nextToken(); if (paths.getNodeFromGraph(child) != null) { findPath(child, resultHistory); } } } public boolean inList(ArrayList<Node> resultHistory, ArrayList<ArrayList<Node>> allPaths) { for (int i = 0; i < allPaths.size();i++) { if (allPaths.get(i).equals(resultHistory)) { return true; } } return false; } Problem is, I don't think it works for all paths, since I can't find certain paths inside it. Although as the dataset is 900 nodes, I am unable to find a pattern! Other questions on Stack seem to be somewhat more specialized and as such I attempted to build my own algorithm!
Can anyone either suggest a superior way to perform this, or tell me what I've done wrong? If the algorithms correct, what would be the best way to withdraw all the paths between two nodes?
EDIT: I now realize that new paths don't get created from child nodes of the original, how would I make it so it does?