I am using depth first search on an undirected graph to find paths from a starting node to an ending node. All the nodes along the path are stored in an ArrayList. But since there can be multiple paths going from start to end, I decided to store each of the ArrayLists that contain the nodes along the paths to another ArrayList, So the second ArrayList should contain all the solution ArrayLists.
However, when I tested the code out, it always ends up with the ArrayLists been empty for some reason, and I am not sure when that is. This is my code for the DFS traversal:
private void pathDepthFirstSearch(Graph graph, GraphNode u, GraphNode v) throws GraphException {
listOfNodes.add(u); //Adds the starting node to the ArrayList
u.setMark(true); //Marks it as visited.
if(u.getName() == v.getName()) { //Managed to get to the end node.(.getName() returns int values).
listOfSolutions.add(listOfNodes); //Add this Path solution to the ArrayList that contains a list of solutions.
numOfSolutions++; //Number of solutions increment by 1.
} else {
for (Iterator<GraphEdge> iter = graph.incidentEdges(u); iter.hasNext();) {
GraphEdge nextEdge = iter.next();
GraphNode secondEndPoint = nextEdge.secondEndpoint();
if(secondEndPoint.getMark() == false) { //Checks if the end point of the edge has been visited or not, if not, then call the method recursively.
pathDepthFirstSearch(graph,secondEndPoint, v);
}
}
}
listOfNodes.remove(u); //Finished exploring u, so remove it from the Solution ArrayList.
u.setMark(false); //Mark as un-visited.
}
And the code for calling the function with startNode and endNode specified:
private List<GraphNode> listOfNodes = new ArrayList<GraphNode>(); //The ArrayList to store one path solution.
private List<List<GraphNode>> listOfSolutions = new ArrayList<>(); //The ArrayList to store all the ArrayList path solutions.
public Iterator<GraphNode> solve() throws GraphException {
GraphNode startNode = new GraphNode(startLoc); //Creates the starting node.
GraphNode endNode = new GraphNode(endLoc); //Creates the end node.
pathDepthFirstSearch(graph, startNode, endNode);
//returns one of the solutions from the ArrayList of solutions (listOfSolutions)
//depending on if we want the longest or shortest path. If the list is empty,
//then null is returned instead.
}
After running this in my main function that prints out the nodes from the ArrayList that is returned from the solve() method, I get the message "no solution is found", which I set it to only happen when the method returned null.
How come the ArrayList is empty, even though in the DFS method, nodes should have been added to it, and then the list is added to the listOfSolutions?