对于一个有向图,请实现一个算法,找出两点之间是否存在一条路径。
给定图中的两个结点的指针UndirectedGraphNode* a,UndirectedGraphNode* b(请不要在意数据类型,图是有向图),请返回一个bool,代表两点之间是否存在一条路径(a到b或b到a)。
-------------------------
思路:实质实现图的广度优先遍历(BFS),关键记录被访问的节点,以下给出两种方法
一种不用记录,一种借助map。
/*
struct UndirectedGraphNode {
int label;
vector<struct UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {}
};*/
class Path {
public:
bool checkPath(UndirectedGraphNode* a, UndirectedGraphNode* b) {
// write code here
if (!a || !b)
return false;
return checkSingle(a, b) || checkSingle(b, a);
}
private:
bool checkSingle(UndirectedGraphNode* a, UndirectedGraphNode* b){
queue<struct UndirectedGraphNode *> que;//BFS工作队列
que.push(a);
while (!que.empty()){
//直到队空
UndirectedGraphNode* t = que.front();
que.pop();//出队
if (t == b)
return true;
//t的所有邻接点进队,晴空邻接点
vector<struct UndirectedGraphNode *>::iterator it;
for (it = t->neighbors.begin(); it!=t->neighbors.end(); ++it){
//入队
que.push(*it);
}
t->neighbors.clear();
}
return false;
}
};
-----------------------------
以下使用map记录访问标记:
/*
struct UndirectedGraphNode {
int label;
vector<struct UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {}
};*/
class Path {
public:
bool checkPath(UndirectedGraphNode* a, UndirectedGraphNode* b) {
// write code here
if (!a || !b)
return false;
return checkSingle(a, b) || checkSingle(b, a);
}
private:
bool checkSingle(UndirectedGraphNode* a, UndirectedGraphNode* b){
queue<struct UndirectedGraphNode *> que;
map<UndirectedGraphNode*,bool> visited;
que.push(a);
while (!que.empty()){
UndirectedGraphNode* cur = que.front();
que.pop();
if (cur == b)
return true;
visited[cur] = true;
//邻接点进队
vector<struct UndirectedGraphNode *>::iterator it;
for (it = cur->neighbors.begin(); it!=cur->neighbors.end(); ++it){
//若未访问过入队
if (!visited[*it])
que.push(*it);
}
}
return false;
}
};