Skip to content

Instantly share code, notes, and snippets.

@dboyliao
Created May 29, 2016 17:17
Show Gist options
  • Save dboyliao/d5e01476e7a5521c5a43f3919db63d3c to your computer and use it in GitHub Desktop.
Save dboyliao/d5e01476e7a5521c5a43f3919db63d3c to your computer and use it in GitHub Desktop.
Simple implementation of DFS (Depth First Search)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def DFS(graph, root_node = "root"):
stack = []
children = graph[root_node]
stack = children + stack
print(root_node)
while len(stack) > 0:
node = stack.pop(0)
print(node)
children = graph[node]
stack = children + stack
"""
example:
graph = {"a":["b", "c"], "b":["d", "e"], "c":[], "d":[], "e":[]}
DFS(graph, root_node = "a")
# a
# b
# d
# e
# c
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment