使用深度优先搜索在树中查找节点

时间:2016-11-26 02:54:32

标签: java algorithm tree depth-first-search

我正在尝试使用Depth First搜索来查找树中的顶点/节点。我能够创建DFS算法,但我不知道如何将树转换为代码,以便我可以通过算法处理它,如下面的链接 JavaScript Depth-first search

这就是我能做的事情

dt1 = new Date('2016-01-21 20:00:00');
dt2 = new Date('2016-01-24 09:00:00');
dif = dt2-dt1;
dif = dif / ( 1000 * 60 * 60 * 24 );
days = Math.ceil(dif);
var total = 0;

if (days > 0) {
  total = 25 + ( (days-1) * 10 ) // total = <first day with prequote 25 and then others days are 10 bucks>
}
console.log(total); // total of amout to be paid

这是树结构。

Vertex nodeA = new Vertex();
    Vertex nodeB = new Vertex();
    Vertex nodeC = new Vertex();
    Vertex nodeD = new Vertex();
    Vertex nodeE = new Vertex();
    Vertex nodeF = new Vertex();
    Vertex nodeG = new Vertex();
    Vertex nodeH = new Vertex();

    nodeA.name = "a";
    nodeB.name = "b";
    nodeC.name = "c";
    nodeD.name = "d";
    nodeE.name = "e";
    nodeF.name = "f";
    nodeG.name = "g";
    nodeH.name = "h";

    nodeA.nextNeighbor.add(nodeB);
    nodeA.nextNeighbor.add(nodeC);
    nodeB.nextNeighbor.add(nodeD);
    nodeB.nextNeighbor.add(nodeE);
    nodeB.nextNeighbor.add(nodeF);
    nodeC.nextNeighbor.add(nodeG);
    nodeG.nextNeighbor.add(nodeH);

这是我的代码

    a
   / \
  b   c
 /|\   \
d e f   g
        |
        h

1 个答案:

答案 0 :(得分:0)

你的意思是这样的吗?

public enum State {
     Unvisited, Visited, Visiting;
   } 
// let the start node and the end node be both the nodes.

// Implementation using  DFS.
     public static boolean search(Graph g, Node start, Node end) { 
           LinkedList<Node> stack = new LinkedList<Node>(); // operates as Stack
            for (Node u : g.getNodes()) {
             u.state = State.Unvisited;
            }
            start.state = State.Visiting;
            stack.add(start);
            Node u;
            while(!stack.isEmpty()) 
            {
                  u = stack.removeFirst(); // i.e., pop()
                  if (u != null) {
                    for (Node v : u.getAdjacent()) {
                      if (v.state == State.Unvisited) {
                           if (v == end) {
                                return true;
                            } 
                            else {
                              v.state = State.Visiting;
                              stack.add(v);
                            }
                       }
                    }
               u.state = State.Visited;
                  }
            }
    return false;
    }