4.1 Route Between Nodes:

Given a directed graph, design an algorithm to find out whether there is a route between two nodes.


In [13]:
Graph = {'A': ['B', 'C', 'D'], 'B': ['C', 'D', 'E'], 'C':['D', 'E', 'F'], 'D':['A', 'B']}

def check_route(tree, node0, node1):
    queue = []
    queue.append(node0)
    visits = {}
    while len(queue) > 0:
        print(queue)
        cur = queue.pop(0)
        dests = tree[cur]
        
        if node1 in dests:
            return True
        
 
        if not visits.get(cur, False): # check already visiting
            queue = tree[cur] + queue
        else:
            visits[cur] = True
        print(visits)   
    return False
        
print(check_route(Graph, 'A', 'F'))


['A']
{}
['B', 'C', 'D']
{}
['C', 'D', 'E', 'C', 'D']
True

In [ ]:


In [ ]: