亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用廣度優先搜索:如何到達終點頂點?

使用廣度優先搜索:如何到達終點頂點?

月關寶盒 2022-09-14 17:30:23
我不確定為什么我的代碼沒有返回正確的路徑頂點。它返回[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);

        }

    }

}


查看完整回答
反對 回復 2022-09-14
  • 1 回答
  • 0 關注
  • 69 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號