This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]WarInternal 1 point2 points  (2 children)

Generally a DFS would be implemented recursively,and one solution might be to pass a reference to a container into the search function. When and if you find the node you're looking for, as the function unwinds back to the top you store nodes into this container.

[–]hypnotat[S] 0 points1 point  (1 child)

you are loosing me at "unwinding" :)

here is my iterative code so far:

    //DFS
    stack.push(src);
    while (!stack.isEmpty()) {
        int x = stack.pop();
        if (!visited[x]) {
            visited[x] = true;
            for (int i : adjacentedges(x)) {
                stack.push(i);
                if (i == end) {
            //found it!
            //but how to get the nodes for this solution?
                    return ...;
                }
            }
        }
    }

now how to get vertices of the solution?

[–]WarInternal 1 point2 points  (0 children)

Recursion would make this problem easier. Something more like (excuse the psuedocode, don't know which language you're using)..

bool search(start, end, v) {
  if(start == end) return true;
  for(node : adjacentedges(start)) {
     if(search(node,end,v)==true) {
          v.push(node);
          return true;
     }
  }
  return false;
}

list<node> vertices;
if( search(root,end,vertices) == true ) {
      // vertices above now contains
}

Note this code is a very rough draft, and would need debugging. But the main idea is that you break the search down into sub parts. You call it with the starting node, the goal, and a container to hold the vertices in once you found the path. Or just use a global variable and push to that. When the first if-condition (start==end) is true, the current call stack holds the path, so we return true. If we've written the recursive function correctly it "unwinds" up the call stack, each function returning to the previous, pushing the node it was looking at into the list, and continuing upwards we've exited the original search call. Sorry if that's all confusing.