Last active
July 5, 2016 07:06
-
-
Save wesalvaro/08060dcdadc6c897aa0082f2bbfe1e65 to your computer and use it in GitHub Desktop.
BFS and DFS for PyGraphviz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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