我有一个赋值,其中我们有一个顶点数组,每个顶点都有一个带有相邻顶点的数组列表。目标是使用查找从第一个顶点到最后一个顶点的路径递归。 一旦深度优先搜索算法到达目标顶点,它就将其添加到解决方案路径(双向链接列表),和 然后递归地将直接路径上的所有顶点添加回源顶点。 这是我的代码到目前为止(而不是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;
}
答案 0 :(得分:0)
你可以这样做:
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 []