2013-10-12 157 views
4

我想在JavaScript中實現DFS,但我遇到了一些問題。這裏是我的算法類:JavaScript深度優先搜索

"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

+0

在哪裏'定義()'函數來自? –

+0

@Sniffer定義只是將功能封裝成AMD模塊。這就是你構建JavaScript代碼的方式(單向)。 –

+0

我明白了,但它從哪裏來?一個外部庫? –

回答

4

的問題是你的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接受多個孩子(可能要改名字太):

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

是的,這是問題所在。我可能不會看到這一點。 –