我正在对无向图进行深度优先搜索,以查找从起始节点到结束节点的路径。路径上的所有节点都存储在ArrayList中。但是由于从头到尾可以有多个路径,所以我决定存储每个ArrayList,这些ArrayList包含沿着到另一个ArrayList的路径的节点,因此第二个ArrayList应该包含所有解决方案ArrayLists。
但是,当我测试代码时,由于某种原因,它总是以ArrayLists为空而结束,但我不确定何时。 这是我进行DFS遍历的代码:
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.
}
以及用于指定startNode和endNode的函数调用代码:
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.
}
在我的主要函数中运行此函数后,该函数从solve()方法返回的ArrayList中打印出节点,然后得到消息“找不到解决方案”,我将其设置为仅在方法返回时发生空。
即使在DFS方法中,应该已经将节点添加到ArrayList,然后将列表添加到listOfSolutions,为什么ArrayList是空的?