JavaScript的深度优先搜索

编程入门 行业动态 更新时间:2024-10-06 14:23:07
本文介绍了JavaScript的深度优先搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想在JavaScript执行DFS,但我有一个小问题。这是我的算法类:

I am trying to implement DFS in JavaScript but I am having a little problem. Here is my Algorithm class:

"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; } } }; }; });

从而重新$ P $我Node类psents图中的一个节点

My Node class which represents a single node in the graph:

"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; }; }; });

我创建这样的树:

I create a tree like this:

"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)); }; }; });

我看未定义在日志中。我不知道为什么我的code是停在4,而不是持续的。

I see undefined in the logs. I am not sure why my code is stopping at 4 and not continuing.

推荐答案

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

The problem is your addChild() method only expects one parameter, but you are passing in multiple nodes to it.

更改您的通话code到:

Change your calling code to:

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接受多个孩子(可能要改名字太):

Or you can change addChild to accept multiple children (probably want to change the name too):

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

更多推荐

JavaScript的深度优先搜索

本文发布于:2023-11-29 02:02:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644849.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:深度   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!