Skip to content

Instantly share code, notes, and snippets.

@zenja
Created December 15, 2013 22:23
Show Gist options
  • Save zenja/7979093 to your computer and use it in GitHub Desktop.
Save zenja/7979093 to your computer and use it in GitHub Desktop.
Sample DFS implementation in Python for a tree using adjacency list
from collections import defaultdict
graph = defaultdict(list)
visited = []
for edge in [[1,2], [1,7], [1,8], [2,3], [2,6], [3,4], [3,5], [8,9], [8,12], [9,10], [9,11]]:
graph[edge[0]].append(edge[1])
graph[edge[1]].append(edge[0])
def visit(graph, visited):
_visit(1, graph, visited)
def _visit(node, graph, visited):
if node not in visited:
visited.append(node)
for child in graph[node]:
_visit(child, graph, visited)
visit(graph, visited)
print visited
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment