【 声明:版权所有,转载请标明出处,请勿用于商业用途。 联系信箱:libin493073668@sina.com】
题目描述
对于一个有向图,请实现一个算法,找出两点之间是否存在一条路径。
给定图中的两个结点的指针UndirectedGraphNode* a,UndirectedGraphNode* b(请不要在意数据类型,图是有向图),请返回一个bool,代表两点之间是否存在一条路径(a到b或b到a)。
思路
一道简单的图的遍历问题,对于已经访问过的结点我们要做标记,防止死循环
/*
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==nullptr)
return false;
if(b==nullptr)
return false;
if(a == b)
return true;
return hasPath(a,b) || hasPath(b,a);
}
bool hasPath(UndirectedGraphNode *a,UndirectedGraphNode *b)
{
queue<UndirectedGraphNode*> Q;
map<int,bool> vis;
Q.push(a);
vis[a->label] = true;
while(!Q.empty())
{
UndirectedGraphNode *cur = Q.front();
Q.pop();
if(cur==b)
return true;
for(UndirectedGraphNode *node:cur->neighbors)
{
if(vis[node->label]==true)
continue;
vis[node->label] = true;
if(node==b)
return true;
Q.push(node);
}
}
return false;
}
};