我正在上面的图中运行广度优先搜索,以查找从节点0
到节点6
的最短路径。
我的代码
public List<Integer> shortestPathBFS(int startNode, int nodeToBeFound){
boolean shortestPathFound = false;
Queue<Integer> queue = new LinkedList<Integer>();
Set<Integer> visitedNodes = new HashSet<Integer>();
List<Integer> shortestPath = new ArrayList<Integer>();
queue.add(startNode);
shortestPath.add(startNode);
while (!queue.isEmpty()) {
int nextNode = queue.peek();
shortestPathFound = (nextNode == nodeToBeFound) ? true : false;
if(shortestPathFound)break;
visitedNodes.add(nextNode);
System.out.println(queue);
Integer unvisitedNode = this.getUnvisitedNode(nextNode, visitedNodes);
if (unvisitedNode != null) {
queue.add(unvisitedNode);
visitedNodes.add(unvisitedNode);
shortestPath.add(nextNode); //Adding the previous node of the visited node
shortestPathFound = (unvisitedNode == nodeToBeFound) ? true : false;
if(shortestPathFound)break;
} else {
queue.poll();
}
}
return shortestPath;
}
我需要追踪BFS算法到达节点6的路径,例如[0,3,2,5,6]
。为此,我创建了一个名为shortestPath
的列表,试图存储已访问节点的前一个节点,以获取节点列表。参考资料
但它似乎无法正常工作。最短路径是[0,3,2,5,6]
。
在列表中,我得到的是Shortest path: [0, 0, 0, 0, 1, 3, 3, 2, 5]
。
它部分正确但会多出一个1
。
如果我再从shortestPath
列表的第一个元素0
开始遍历和回溯。例如1
没有到3
的边缘,因此我回溯并从0
移动到3
到5
,我将得到答案,但不确定是否正确的方法。
获取最短路径节点的理想方法是什么?