1 回答

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超7個(gè)贊
變量和變量具有不同的用途,但在您的情況下,它們以相同的方式進(jìn)行更新,這是不正確的。queuevisited
很快,您將在處理其父節(jié)點(diǎn)時(shí)將節(jié)點(diǎn)添加到 (這意味著在將來(lái)的某個(gè)時(shí)間點(diǎn),該節(jié)點(diǎn)也希望得到處理)。同時(shí),只有在處理完節(jié)點(diǎn)(將其子節(jié)點(diǎn)添加到隊(duì)列)后,才將其添加到 該節(jié)點(diǎn)。queuevisited
您的循環(huán)應(yīng)如下所示(請(qǐng)注意插入的位置)。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);
}
}
}
添加回答
舉報(bào)