[英]Using breadth first search: how do I get to the end vertex?
I am not sure why my code is not returning the correct path vertices. 我不确定为什么我的代码没有返回正确的路径顶点。 It is returning [abc] instead of [acf],and I don't know why. 它返回[abc]而不是[acf],我不知道为什么。 Is there something I'm missing here or doing wrong in my algorithm? 我的算法中是否有我遗漏或做错的事情? Note: getNeighbors(String vertex) returns the connecting edges for the vertex in its parameter. 注意:getNeighbors(String vertex)返回其参数中顶点的连接边。
This is the test: My code stops at "assertEquals("c", route.next())" because it is returning "b" instead of a "c". 这是测试:我的代码停在“assertEquals(”c“,route.next())”因为它返回“b”而不是“c”。 my code' current output is [abc] and the expected is [acf] 我的代码'当前输出是[abc],预期是[acf]
public class PathingTest {
@Test
public void testPathing(){
Graph cycle = new Graph("graphs/cycle.json");
Iterator<String> route = cycle.getRoute("d", "b").iterator();
assertEquals("d",route.next());
assertEquals("b",route.next());
assertFalse(route.hasNext());
Graph tree = new Graph("graphs/tree.json");
route = tree.getRoute("a", "f").iterator();
assertEquals("a",route.next());
assertEquals("c", route.next());
assertEquals("f", route.next());
assertFalse(route.hasNext());
Graph disconnected = new Graph("graphs/disconnected.json");
assertEquals(null, disconnected.getRoute("a", "f"));
}
}
The queue
variable and the visited
variable have different purposes, but in your case, they get updated in the same way, which is not correct. queue
变量和visited
变量有不同的用途,但在您的情况下,它们会以相同的方式更新,这是不正确的。
Shortly, you add a node to the queue
while processing its parent (which means that at some point in the future, that node is expecting to be processed too). 不久,你将节点添加到所述queue
在处理其父(这意味着在未来某一时刻,该节点期望被处理过)。 Meanwhile, you only add a node to visited
only after you have processed it (added its children to the queue). 同时,只有在处理完节点后才将其添加到visited
的节点(将其子节点添加到队列中)。
Your while
loop should look like this (please notice the position of the insertion into visited
). 你的while
循环应该是这样的(请注意插入到visited
的位置)。
while (!queue.isEmpty()) {
String current = queue.remove();
path.add(current);
visited.add(current);
if (current == end) {
return path;
}
Iterator<String> neighbors = getNeighbors(start).iterator();
while (neighbors.hasNext()) {
String n = neighbors.next();
if (!visited.contains(n)) {
queue.add(n);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.