Last active
July 6, 2020 16:55
-
-
Save sonnyksimon/8d4d610a9cbeb3cf35a9f61f624cac53 to your computer and use it in GitHub Desktop.
depth-first search in Python
This file contains hidden or 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
# Using a dictionary to act as an adjacency list | |
graph = { | |
'A' : ['B','C'], | |
'B' : ['D', 'E'], | |
'C' : ['F'], | |
'D' : [], | |
'E' : ['F'], | |
'F' : [] | |
} | |
# visited: Set to keep track of visited nodes. | |
def dfs(visited, graph, node): | |
if node not in visited: | |
print (node) | |
visited.add(node) | |
for neighbour in graph[node]: | |
dfs(visited, graph, neighbour) | |
def iterative_dfs(visited, graph, node): | |
stack = [node] | |
while stack: | |
node = stack.pop() | |
if node not in visited: | |
print (node) | |
visited.add(node) | |
for neighbour in reversed(graph[node]): | |
stack.append(neighbour) | |
# Driver Code | |
dfs(set(), graph, 'A') | |
iterative_dfs(set(), graph, 'A') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment