Created
July 7, 2018 19:30
-
-
Save john-nash-rs/1da6eb1085cf99b3540f7b3ba5390d4c to your computer and use it in GitHub Desktop.
Depth First Search Python Implementation : Prints all the nodes of the graph
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
def depth_first_search(graph, start_node): | |
visited_neighbours = set() #Keep track of the node we have visited like breadcrumbs to know the path | |
neighbours = [start_node] #list to store the neighbors. We will start with neigbors of void, the start node | |
while (len(neighbours) != 0): #All the elements will be transversed by the time we have this list size as zero | |
neighbour = neighbours.pop() #pop will take out randomly any one element and deletes from the list | |
if neighbour not in visited_neighbours: | |
visited_neighbours.add(neighbour) | |
new_prospected_neighbours = graph[neighbour] | |
#Need to remove neighbours which are already visted | |
new_neighbours = new_prospected_neighbours - visited_neighbours | |
neighbours.extend(new_neighbours) | |
return visited_neighbours | |
depth_first_search(graph, 'A') | |
#output: {'A', 'B', 'C', 'D', 'E', 'F', 'G'} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment