思路: 这个题目考察的其实是有向图的遍历,图的遍历分为深度优先遍历和广度优先遍历,深度优先遍历用堆栈实现,广度优先遍历用队列实现,在该题目中给出了每个节点的子节点,所以最好用广度优先遍历。
图的广度优先遍历和树的层次遍历类似,但是不是完全相同,因为图是连通的,所以我们必须去标志那个节点被访问过,那个节点没有被访问过,最后如果全部访问完以后,还没有找到a到b的路径,则返回false。
注意:
(1)图中有环,记得标记是否被访问
(2)要分别检测两个方向(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)
{
return checkNode(a,b) || checkNode(b,a);
}
bool checkNode(UndirectedGraphNode* a,UndirectedGraphNode* b)
{
if(a==nullptr || b==nullptr)
{
return false;
}
if(a==b)
{
return true;
}
map<UndirectedGraphNode*, bool> checkMap;
queue<UndirectedGraphNode*> queue;
queue.push(a);
while(!queue.empty())
{
UndirectedGraphNode* temp=queue.front();
checkMap[temp]=true;
for(int i=0;i<temp->neighbors.size();++i)
{
if(temp->neighbors[i]==b)
{
return true;
}
if(temp->neighbors[i] && checkMap[temp->neighbors[i]]!=true)
{
queue.push(temp->neighbors[i]);
}
}
queue.pop();
}
return false;
}
};