4.2 Given a directed graph, design an algorithm to find out whether there is a route between two nodes.
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct GraphNode {
enum State {unvisited, visited, visiting} state;
vector<GraphNode*> adjacentNodes;
GraphNode(void) : state(unvisited) {}
};
void initNodeState(vector<GraphNode> &g) {
for (GraphNode &node : g) {
node.state = GraphNode::unvisited;
}
}
bool BFS(GraphNode *a, GraphNode *b) {
queue<GraphNode*> q;
a->state = GraphNode::visiting;
q.push(a);
while (!q.empty()) {
GraphNode *curr = q.front();
q.pop();
for (GraphNode *next : curr->adjacentNodes) {
if (next->state == GraphNode::unvisited) {
if (next == b) {
return true;
} else {
next->state = GraphNode::visiting;
q.push(next);
}
}
}
}
return false;
}
int main() {
vector<GraphNode> g(4);
g[0].adjacentNodes.push_back(&g[1]);
g[1].adjacentNodes.push_back(&g[2]);
initNodeState(g);
if (BFS(&g[0], &g[2])) {
cout << "Connected" << endl;
}
return 0;
}