"Is There a Route Between Two Nodes in a Directed Graph?"

This technical problem deals with finding a route between two nodes in a directed graph. An algorithm is designed to determine whether there is a path between the two nodes.

Problem

Given a directed graph, design an algorithm to find out whether there is a route between two nodes.
Example:
Input:
Node 1: A
Node 2: B
Output:
true

Solution

This solution is in C++. Our A.I. can create solutions in multiple languages.
by kayakane
#include <iostream>
#include <vector>
#include <queue>

using namespace std;

class Node {
public:
    Node(int val) : val(val) {}
    int val;
    vector<Node*> neighbors;
};

bool isRoute(Node* start, Node* end) {
    if (start == end) return true;
    queue<Node*> q;
    q.push(start);
    while (!q.empty()) {
        Node* curr = q.front();
        q.pop();
        for (Node* neighbor : curr->neighbors) {
            if (neighbor == end) return true;
            q.push(neighbor);
        }
    }
    return false;
}

int main() {
    Node* a = new Node(1);
    Node* b = new Node(2);
    Node* c = new Node(3);
    Node* d = new Node(4);
    Node* e = new Node(5);
    Node* f = new Node( 6);
    a->neighbors.push_back(b);
    a->neighbors.push_back(c);
    b->neighbors.push_back(d);
    c->neighbors.push_back(e);
    d->neighbors.push_back(f);
    cout << isRoute(a, f) << endl;
    cout << isRoute(a, e) << endl;
    cout << isRoute(a, a) << endl;
    cout << isRoute(a, b) << endl;
    cout << isRoute(a, c) << endl;
    cout << isRoute(a, d) << endl;
    cout << isRoute(a, e) << endl;
    cout << isRoute(a, f) << endl;
    return 0;
}

A.I. Evaluation of the Solution

The candidate's solution is complete and solves the problem. The approach is to use a queue to keep track of the nodes that have been visited. If the end node is found in the neighbors of the current node, then there is a route between the two nodes.

Evaluated at: 2022-11-26 14:15:50