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;
}
本文介绍了一种用于判断有向图中两个节点间是否存在路径的算法——广度优先搜索(BFS)。通过使用队列结构,该算法能够有效地遍历图中的所有节点,并确保每个节点仅被访问一次。文章还提供了一个示例代码,展示了如何初始化图节点状态,并利用BFS算法检查特定起点到终点的连通性。
1121

被折叠的 条评论
为什么被折叠?



