gpt4 book ai didi

JavaScript 深度优先搜索

转载 作者:搜寻专家 更新时间:2023-11-01 04:09:31 28 4
gpt4 key购买 nike

我正在尝试用 JavaScript 实现 DFS,但我遇到了一个小问题。这是我的算法类:

"use strict";

define([], function () {

return function () {

var that = this;

this.search = function (searchFor, node) {
if (searchFor === node.getValue()) {
return node;
}
var i, children = node.getChildren(), child, found;
for (i = 0; i < children.length; i += 1) {
child = children[i];
found = that.search(searchFor, child);
if (found) {
return found;
}
}
};

};

});

我的节点类代表图中的单个节点:

"use strict";

define([], function () {

return function (theValue) {
var value = theValue,
children = [];

this.addChild = function (theChild) {
children.push(theChild);
};

this.hasChildren = function () {
return children.length > 0;
};

this.getChildren = function () {
return children;
};

this.getValue = function () {
return value;
};
};

});

我创建了这样一棵树:

enter image description here

"use strict";

define(["DFS/Node", "DFS/Algorithm"], function (Node, Algorithm) {

return function () {

this.run = function () {
var node1 = new Node(1),
node2 = new Node(2),
node3 = new Node(3),
node4 = new Node(4),
node5 = new Node(5),
node6 = new Node(6),
node7 = new Node(7),
node8 = new Node(8),
node9 = new Node(9),
node10 = new Node(10),
node11 = new Node(11),
node12 = new Node(12),
dfs = new Algorithm();

node1.addChild(node2, node7, node8);
node2.addChild(node3, node6);
node3.addChild(node4, node5);
node8.addChild(node9, node12);
node9.addChild(node10, node11);

console.log(dfs.search(5, node1));
};

};

});

我在日志中看到未定义。我不确定为什么我的代码在 4 处停止而不继续。

enter image description here

最佳答案

问题是您的 addChild() 方法只需要一个参数,但您将多个节点传递给它。

将您的调用代码更改为:

node1.addChild(node2);
node1.addChild(node7);
node1.addChild(node8);

node2.addChild(node3);
node2.addChild(node6);

node3.addChild(node4);
node3.addChild(node5);

node8.addChild(node9);
node8.addChild(node12);

node9.addChild(node10);
node9.addChild(node11);

或者您可以更改 addChild 以接受多个 child (可能也想更改名称):

this.addChildren = function () {
for (var i = 0; i < arguments.length; i++) {
children.push(arguments[i]);
}
};

关于JavaScript 深度优先搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19338974/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com