Skip to content

Instantly share code, notes, and snippets.

@rootVIII
Last active May 30, 2022 16:20
Show Gist options
  • Save rootVIII/46be07e746bbf0515cfa0febdb02d9d0 to your computer and use it in GitHub Desktop.
Save rootVIII/46be07e746bbf0515cfa0febdb02d9d0 to your computer and use it in GitHub Desktop.
Python Depth First Search
#! /usr/bin/python3
# rootVIII - my DFS
class Dfs:
def __init__(self, graph, top_node):
self.graph = graph
self.route_travelled = []
self.__trace_route(top_node)
def get_route_travelled(self):
return self.route_travelled
def __trace_route(self, node):
# If node not yet visited, add it to
# the route travelled list
if node not in self.route_travelled:
self.route_travelled.append(node)
# Loop through the key's value which
# is a list of it's neighboring nodes
for friend in self.graph[node]:
# recursively call with each
# neighbor in the list
self.__trace_route(friend)
if __name__ == "__main__":
graph1 = {
'A': ['B'],
'B': ['C'],
'C': ['A', 'D'],
'D': []
}
dfs = Dfs(graph1, 'C')
print(dfs.get_route_travelled())
graph2 = {
'1': ['2', '3'],
'2': ['4', '5'],
'3': ['5'],
'4': ['6'],
'5': ['6'],
'6': ['7'],
'7': []
}
dfs = Dfs(graph2, '1')
print(dfs.get_route_travelled())
graph3 = {
'A': ['B', 'S'],
'B': ['A'],
'C': ['D', 'E', 'F', 'S'],
'D': ['C'],
'E': ['C', 'H'],
'F': ['C', 'G'],
'G': ['F', 'S'],
'H': ['E', 'G'],
'S': ['A', 'C', 'G']
}
dfs = Dfs(graph3, 'A')
print(dfs.get_route_travelled())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment