【发布时间】:2020-11-12 14:15:59
【问题描述】:
所以我正在尝试实现一个简单的 BFS 搜索来解决迷宫问题。我正在使用的代码顶部有一个 test_graph。当我遍历这段代码时:
for (var neighbour in graph[vertex])
{
console.log("neighbour :", neighbour);
console.log("path :", path)
let new_path = path;
new_path.push(neighbour);
console.log("new path :", new_path);
}
我得到了输出:
neighbour : A
bfs.js:38 path : ["start"]
bfs.js:43 new path : (2) ["start", "A"]
bfs.js:37 neighbour : B
bfs.js:38 path : (2) ["start", "A"]
bfs.js:43 new path : (3) ["start", "A", "B"])
但是,我希望 new_path 的第二次迭代是 ["start", "B"] 而不是 ["start", "A", "B"]。我想将邻居(A和B)每个附加到“start”以创建数组[“start”,“A”]和[“start”,“B”]并将其推入队列。
这里是完整的代码:
const test_graph = {
start: {A: 1, B: 1},
A: {C: 1, D: 1},
B: {A: 1, D: 1},
C: {D: 1, finish: 1},
D: {finish: 1},
finish: {}
};
// Breadth-first search
const BFS = (graph, start, fin) => {
var queue = [];
queue.push([start]);
var visited = [];
while (Array.isArray(queue) && queue.length)
{
// get first path on queue
var path;
path = queue.shift();
//console.log(path); // ["start"]
// get the last node in the path
var vertex = path[path.length - 1];
//console.log(vertex); // start
// if end
if (vertex == fin)
{
return path;
}
else if (!visited.includes(vertex))
{
// for all adjvant nodes, construct new path and push into queue
for (var neighbour in graph[vertex])
{
console.log("neighbour :", neighbour);
console.log("path :", path)
let new_path = path;
new_path.push(neighbour);
queue.push(new_path);
console.log("new path :", new_path);
}
}
return;
}
}
(return 就是为了解决这个问题)
【问题讨论】:
标签: javascript arrays loops object breadth-first-search