Wednesday 15 May 2019

DFS

graph = {'A' : set(['G','B']),
         'B' : set(['C','D','A']),
         'C' : set(['F','D','B']),
         'D' : set(['B','C']),
         'E' : set(['F']),
         'F' : set(['E','C']),
         'G' : set(['A']),
        }
print (graph)

def depth_first_search(graph, start_node):
    visited_neighbours = set()
    neighbours = [start_node] 
    while (len(neighbours) != 0):
        neighbour = neighbours.pop() 
        if neighbour not in visited_neighbours:
            visited_neighbours.add(neighbour)
            new_prospected_neighbours = graph[neighbour]
            new_neighbours = new_prospected_neighbours - visited_neighbours
            neighbours.extend(new_neighbours)
    return visited_neighbours         
depth_first_search(graph, 'A')

No comments:

Post a Comment