我不確定為什么我的代碼沒有返回正確的路徑頂點。它返回[a b c]而不是[a c f],我不知道為什么。我在這里是否遺漏了什么或在我的算法中做錯了什么?注: getNeighbors(字符串頂點)在其參數中返回頂點的連接邊。這是測試:我的代碼停止在“斷言等式(”c“,route.next())”,因為它返回“b”而不是“c”。我的代碼的當前輸出是 [a b c],預期的是 [a c f]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")); }}
1 回答

牧羊人nacy
TA貢獻1862條經驗 獲得超7個贊
變量和變量具有不同的用途,但在您的情況下,它們以相同的方式進行更新,這是不正確的。queuevisited
很快,您將在處理其父節點時將節點添加到 (這意味著在將來的某個時間點,該節點也希望得到處理)。同時,只有在處理完節點(將其子節點添加到隊列)后,才將其添加到 該節點。queuevisited
您的循環應如下所示(請注意插入的位置)。whilevisited
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);
}
}
}
添加回答
舉報
0/150
提交
取消