简体   繁体   English

从第一个顶点到最后一个Java递归地进行深度优先搜索

[英]depth first search recursively from first vertex to last java

i have an assignment in which we have an array of vertices, each vertex has an array list with adjacent vertices. 我有一个作业,其中我们有一个顶点数组,每个顶点都有一个包含相邻顶点的数组列表。 the goal is to use find a path from the first vertex to the last recursively. 目标是使用递归方式查找从第一个顶点到最后一个顶点的路径。 Once the depth-first search algorithm reaches the destination vertex it adds it to the solution path(doubly linked list), and then recursively adds all the vertices on the direct path back to the source vertex. 深度优先搜索算法一旦到达目标顶点,便将其添加到求解路径(双向链表)中,然后将直接路径上的所有顶点递归地添加回源顶点。 here is my code so far(instead of solutionPath.add im just printing to console to see what would be added to the linked list with the path) 到目前为止,这是我的代码(而不是solutionPath.add我只是打印到控制台以查看将添加到带有路径的链表中的内容)

private DoublyLinkedList<Vertex> dfs(int firstRoom, int lastRoom, boolean[] 
visited){  
 System.out.println(firstRoom);
 if(visited[lastRoom]== true){


    return pathSolution;


}

Iterator<Edge> n = rooms[firstRoom].getEdgesIterator();
while(n.hasNext()){
    int e= n.next().getAdjacentVertex();

    if(!visited[e]){
         visited[e]=true;
        return dfs(e, lastRoom, visited);   

    }


}   


return pathSolution;


 }

You can do it like this: 您可以这样做:

List dfs(v):
    visited[v] = True
    if v == last_vertex:
        // If v is the last vertex, we can simply return the list containing it
        return [last_vertex]
    for u in neighbors of v:
        if not visited[u]:
             list_from_u = dfs(u)
             // If the list is non-empty, last_vertex is reachable from v
             // and the list contains a valid path to it
             // So we just need to add v to the front of the list and return 
             // the result. Otherwise, there's no path from u to the last_vertex
             // so we do nothing right here and keep looking 
             if not list_from_u.empty():
                  list_from_u.prepend(v)
                  return list_from_u
    // There're was no path to the last_vertex, so we return an empty list
    // to indicate it     
    return []

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM