Determine if a route exists between two nodes in a directed graph

This technical problem involves determining whether a route exists between two nodes in a directed graph. An example input and output are given.

Problem

Given a directed graph, design an algorithm to find out whether there is a route between two nodes.
Example input: 
A -> B
A -> C
B -> D
C -> D
Example output: 
True

Solution

This solution is in Python. Our A.I. can create solutions in multiple languages.
by kayakane
# Solution:
# This is a graph traversal problem. We can use a breadth-first search to find the shortest path between two nodes.
# The solution below is optimal because it uses a queue to store the nodes to visit.
# The queue is implemented using a list.
# The time complexity is O(n) because we visit each node once.
# The space complexity is O(n) because we store each node in the queue.

class Node:
    def __init__(self, name):
        self.name = name
        self.children = []

def find_route(start, end):
    queue = [start]
    visited = set()
    while queue:
        node = queue.pop(0)
        if node == end:
            return True
        visited.add(node)
        for child in node.children:
            if child not in visited:
                queue.append(child)
    return False

a = Node('A')
b = Node('B')
c = Node('C')
d = Node('D')
e = Node('E')
a.children = [b, c]
b.children = [d]
c.children = [d]

print(find_route(a, d))
print(find_route(a, e))

A.I. Evaluation of the Solution

The candidate's solution is correct and uses a breadth-first search to find the shortest path between two nodes. The time complexity is O(n) and the space complexity is O(n).

Evaluated at: 2022-12-01 04:15:53