2013-10-12 2 views
4

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

    }; 

}); 
을 여기 내 알고리즘 클래스입니다

로그에 undefined가 있습니다. 나는 왜 내 코드가 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

네, 그게 문제였습니다. 아마 나는 그것을 보지 못하게 될 것입니다. –