题目描述
对于一个有向图,请实现一个算法,找出两点之间是否存在一条路径。
给定图中的两个结点的指针UndirectedGraphNode* a,UndirectedGraphNode* b(请不要在意数据类型,图是有向图),请返回一个bool,代表两点之间是否存在一条路径(a到b或b到a)。
思路:深度优先搜索或广度优先搜索,为避免图中有环,要记录每个节点是否访问过。
广度优先搜索很适合用来查找最短路径,而深度优先搜索在访问临近节点之前,可能会先深度遍历其中一个临近节点。时间复杂度都是O(n^2)。
1、广度优先搜索
/*
struct UndirectedGraphNode {
int label;
vector<struct UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {}
};*/
class Path {
public:
bool checkPath(UndirectedGraphNode* a, UndirectedGraphNode* b) {
//有向图两个方向都要查看
return check(a, b) || check(b, a);
}
bool check(UndirectedGraphNode *a, UndirectedGraphNode *b) {
if (a == nullptr || b == nullptr) return false;
if (a == b) return true;
//记录每个节点的访问状态
map<UndirectedGraphNode*, bool> isVisted;
//队列实现广度优先搜索
queue<UndirectedGraphNode*> que;
que.push(a);
while (!que.empty()) {
UndirectedGraphNode* tmp = que.front();
isVisted[tmp] = true;
for (auto elem : tmp->neighbors) {
if (elem == b) return true;
if (elem != nullptr && isVisted[elem] != true)
que.push(elem);
}
que.pop();
}
return false;
}
};
2、深度优先搜索(递归)
/*
struct UndirectedGraphNode {
int label;
vector<struct UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {}
};*/
class Path {
public:
bool checkPath(UndirectedGraphNode* a, UndirectedGraphNode* b) {
return check(a, b) || check(b, a);
}
bool check(UndirectedGraphNode* a, UndirectedGraphNode* b) {
if (a == b) return true;
if(a == nullptr || b == nullptr) return false;
isVisted[a] = true;
for (auto elem : a->neighbors) {
if ((isVisted[elem] != true) && check(elem, b))
return true;
}
return false;
}
private:
map<UndirectedGraphNode*, bool> isVisted;
};