Skip to content

Instantly share code, notes, and snippets.

@wesalvaro
Last active July 5, 2016 07:06
Show Gist options
  • Save wesalvaro/08060dcdadc6c897aa0082f2bbfe1e65 to your computer and use it in GitHub Desktop.
Save wesalvaro/08060dcdadc6c897aa0082f2bbfe1e65 to your computer and use it in GitHub Desktop.
BFS and DFS for PyGraphviz
INDEX_BFS = 0
INDEX_DFS = -1
NOOP = lambda x: None
def traverse(graph, nodes, callback, index):
visited = set()
while nodes:
node = nodes.pop(index)
if node not in visited:
visited.add(node)
callback(node)
nodes.extend(graph.successors(node))
return visited
def bfs(graph, nodes, callback=NOOP):
return traverse(graph, nodes, callback, INDEX_BFS)
def dfs(graph, nodes, callback=NOOP):
return traverse(graph, nodes, callback, INDEX_DFS)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment