【发布时间】:2017-06-06 23:37:00
【问题描述】:
我在上图中运行广度优先搜索以找到从Node 0 到Node 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 的列表并尝试存储访问节点的先前节点,以获取节点列表。 Referred
但它似乎不起作用。最短路径为[0,3,2,5,6]
在列表中我得到的是Shortest path: [0, 0, 0, 0, 1, 3, 3, 2, 5]
它部分正确,但给出了额外的 1 。
如果我再次从shortestPath 列表的第一个元素0 开始并开始遍历和回溯。就像1 对3 没有优势,所以我回溯并从0 移动到3 到5,我会得到答案,但不确定这是否是正确的方法。
获取最短路径的节点的理想方法是什么?
【问题讨论】:
-
在此处查看第二个答案:stackoverflow.com/questions/8379785/…
-
第二个答案解释了如何在加权图上运行 BFS
-
它说:所有边的权重相同或没有权重。您可以假设所有边的权重都相同
-
是的,假设所有边的权重相同。现在你将如何获得节点?一个节点 x 还有 3 个具有相同权重的节点。你会穿越哪一个?你怎么知道哪个是最好的。此外,我的问题与答案试图说的完全不同。请再次阅读我的问题。我不是在寻找最短路径,BFS 默认会寻找,我正在寻找打印最短路径的节点。收到了吗?
-
每次访问子节点时保存父节点。假设您从 0 开始。BFS 可能首先访问 8、3 和 1。您将它们的父级保存为 0。然后您访问例如 4、2 和 7。它们的父级将是 8、3 和 1,依此类推。当您到达目标时,您将父母迭代回源。
标签: java algorithm data-structures breadth-first-search