Skip to content

Commit

Permalink
add recursive dfs
Browse files Browse the repository at this point in the history
  • Loading branch information
shaunorpen committed Mar 16, 2020
1 parent 48735f0 commit 862f86e
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions projects/graph/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,15 +125,30 @@ def dfs(self, starting_vertex, destination_vertex):
new_path = [*path, next_vertex]
s.push(new_path)

def dfs_recursive(self, starting_vertex):
def dfs_recursive(self, starting_vertex, destination_vertex):
"""
Return a list containing a path from
starting_vertex to destination_vertex in
depth-first order.
This should be done using recursion.
"""
pass # TODO
def recurse(start, end, path = list(), visited = set()):
if len(path) == 0:
path.append(start)
if path[-1] == end:
return path
else:
last_vertex = path[-1]
if last_vertex not in visited:
visited.add(last_vertex)
for next_vertex in self.vertices[path[-1]]:
new_path = [*path, next_vertex]
recurse(start, end, new_path)

return recurse(starting_vertex, destination_vertex)



if __name__ == '__main__':
graph = Graph() # Instantiate your graph
Expand Down

0 comments on commit 862f86e

Please sign in to comment.