Wikipedia does have some pretty good pseudo-code for circumvention. These crawl algorithms place all nodes in the graph with the order in which they appear in the crawl. Instead, you want to immediately return the path to the target when the target is found.
So, change the Wikipedia algorithm:
( INCORRECT ALGORITHM DELETED WHICH THE OP COMMENTED ON CORRECTLY BELOW )
Here is a Python implementation:
g = { 'A': ['B', 'C', 'D'], 'B': ['C', 'E', 'F'], 'C': ['A'], 'D': ['B', 'F', 'G', 'H'], 'E': ['G'], 'F': ['A', 'F'], 'G': ['H', 'I'], 'H': [], 'I': [] } def DFS(g, v, goal, explored, path_so_far): """ Returns path from v to goal in g as a string (Hack) """ explored.add(v) if v == goal: return path_so_far + v for w in g[v]: if w not in explored: p = DFS(g, w, goal, explored, path_so_far + v) if p: return p return "" # Hack unit test assert DFS(g, 'A', 'I', set(), "") == "ABEGI" assert DFS(g, 'A', 'E', set(), "") == "ABE" assert DFS(g, 'B', 'B', set(), "") == "B" assert DFS(g, 'B', 'B', set(), "") == "B" assert DFS(g, 'A', 'M', set(), "") == "" assert DFS(g, 'B', 'A', set(), "") == "BCA" assert DFS(g, 'E', 'A', set(), "") == ""
The idea here is that you want to find the path from v to goal in column g , given that you have already entered the path in path_so_far . path_so_far should end just before v .
If v is the goal, you can add v to the path so far and that is it.
Otherwise, you will need to examine all the edges emanating from v that have not yet explored the nodes at the other end of the edge. For each of these edges, you can search (recursively) using your path so far plus the current node. If there is no path to the goal from v , you will return an empty path.
It's good that you use recursion to "automatically return" because you pass the extended path to your recursive call.