# CCI题目4-2：判断图中的两个节点是否连通

By | 2012 年 11 月 24 日

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

```
//
//  main.cpp
//  CCI.4.2.Reachable in Graph
//
//  Created by Qiu Xiangyu on 12-11-24.
//

#include
#include
#include
using namespace std;
enum VisitState {
Unvisite = 0,
Visiting = 1,
Visited = 2
};
class GraphNode {
public:
VisitState visiteState;
};
class Graph {

public:
void setAllVisiteState(VisitState targetState);
bool isNodeInGraph(GraphNode *node);
bool isNodeConnectToNode(GraphNode *sourceNode, GraphNode *targetNode) {
if (!isNodeInGraph(sourceNode) || !isNodeInGraph(targetNode)) {
return false;
}
setAllVisiteState(Unvisite);
//unvisit, not visited at all
//visiting, in the queue, but not examed and expaned
//vivited, expanded and visited.
queue q;
q.push(sourceNode);
while (q.size()) {
GraphNode *curNode = q.front();
q.pop();
if (curNode->visiteState == Visited) {
continue;
}
if (curNode == targetNode) {
return true;
}
curNode->visiteState = Visited;
GraphNode *cnode = *it;
if (cnode->visiteState == Unvisite) {
cnode->visiteState = Visiting;
q.push(cnode);
}
}
}
return false;
}
};

int main(int argc, const char * argv[])
{
// insert code here...
std::cout << "Hello, World!\n";
return 0;
}
```