Solution1:我的答案
【这思路不好,容易陷入死循环】利用图的DFS,没有标记点是否被访问过。
【BFS更适合用来查找最短路径】
/*
struct UndirectedGraphNode {
int label;
vector<struct UndirectedGraphNode *> neighbors;
UndirectedGraphNode(int x) : label(x) {}
};*/
class Path {
public:
bool checkPath(UndirectedGraphNode* a, UndirectedGraphNode* b) { //利用深度优先搜索DFS
// write code here
if(a == NULL || b == NULL)
return false;
if(a == b)
return true;
if(my_DFS(a, b) || my_DFS(b, a))
return true;
else
return false;
}
bool my_DFS(UndirectedGraphNode* root, UndirectedGraphNode* target) {
if(root == NULL) return false;
for(int i = 0; i < root->neighbors.size(); i++) {
if(root->neighbors[i] == target) {
return true;
}
else
return my_DFS(root->neighbors[i], target);
}
return false;
}
};
Solution2:广度优先搜索
利用图的BFS
参考网址:https://www.nowcoder.com/profile/9533316/codeBookDetail?submissionId=12693785
20181010整理
/*
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;
if (a==b)
return true;
if (my_BFS(a,b) || my_BFS(b,a))
return true;
else
return false;
}
bool my_BFS(UndirectedGraphNode* a, UndirectedGraphNode* b) {
map<UndirectedGraphNode*, bool> map1;
queue<UndirectedGraphNode*> que;
que.push(a);
while (!que.empty()) {
//读取队列中的头结点
UndirectedGraphNode* ptr = que.front();
map1[ptr] = true;
if (ptr == b)
return true;
for (int i = 0; i < ptr->neighbors.size(); i++) {
if ((ptr->neighbors)[i] == b)
return true;
if (map1[ptr->neighbors[i]] != true)
que.push((ptr->neighbors)[i]);
}
//从队列中删除
que.pop();
}
return false;
}
};
原始代码
/*
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==NULL||b==NULL)
return false;
if(a==b)
return true;
if(my_BFS(a,b) || my_BFS(b,a))
return true;
else
return false;
}
bool my_BFS(UndirectedGraphNode* a, UndirectedGraphNode* b) {
map<UndirectedGraphNode*,bool> map1;
queue<UndirectedGraphNode*> que;
que.push(a);
while(!que.empty())
{
UndirectedGraphNode* ptr=que.front();
map1[ptr]=true;
if(ptr == b)
return true;
for(int i=0;i<ptr->neighbors.size();i++)
{
if((ptr->neighbors)[i]==b)
return true;
if(ptr->neighbors[i]&&map1[ptr->neighbors[i]]!=true)
que.push((ptr->neighbors)[i]);
}
que.pop();
}
return false;
}
};
利用DFS时可以不用标记某一点是否访问过,只不过耗时长一点。在利用BFS时,由于需要把图的点压入到队列中,所以要标记某点是否访问过,否则会超出内存限制。但保险起见还是应该标记下某一点是否访问过。