将所有访问的节点存储在单个列表中对于查找
最短路径,因为最终你无法知道哪些节点是
哪些是指向目标节点的,哪些是死胡同。
您需要做的是让每个节点在路径中存储上一个节点
从起始节点开始。
因此,创建一个
map map<Integer,Integer>parentNodes,而不是这样:
shortestPath.add(nextNode);
do this:
parentNodes.put(unvisitedNode, nextNode);
到达目标节点后,可以遍历该映射以找到返回起始节点的路径:
if(shortestPathFound) { List<Integer> shortestPath = new ArrayList<>(); Integer node = nodeToBeFound; while(node != null) { shortestPath.add(node) node = parentNodes.get(node); } Collections.reverse(shortestPath);}


