Skip to content

Instantly share code, notes, and snippets.

@okaysidd
Last active June 16, 2020 19:55
Show Gist options
  • Save okaysidd/9833344ecd9f3eac04aff42d2569d684 to your computer and use it in GitHub Desktop.
Save okaysidd/9833344ecd9f3eac04aff42d2569d684 to your computer and use it in GitHub Desktop.
def DFS(adj):
def dfs_visit(node, result=None):
if result == None:
result = []
for neighbor in adj[node]:
if neighbor not in seen:
result.append(neighbor)
seen.add(neighbor)
dfs_visit(neighbor, result)
return result
parent = ['A'] # for recording dfs result starting from vertex 'A'
seen = set()
parent.extend(dfs_visit('A'))
return parent
# adjacency list for the graph
adj = {'A':['B','D'], 'B':['C','D'], 'C':[], 'D':['E'], 'E':[]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment