题目描述:
对于本题,本能想到深度优先搜索。递归实现, 一直走到当前路线最后一个节点。当递归回到s节点,并且没有找到t节点,才能认为是不存在路线。图中可能有不同的节点指向同一个节点,这样就需要一个数据结构来保存每一个节点的访问情况,只访问没有访问过的节点,这样才不会超时。
class Solution {
public:
/*
* @param graph: A list of Directed graph node
* @param s: the starting Directed graph node
* @param t: the terminal Directed graph node
* @return: a boolean value
*/
map<DirectedGraphNode*, bool> visited;
bool hasRoute(vector<DirectedGraphNode*> graph, DirectedGraphNode* s, DirectedGraphNode* t) {
// write your code here
if(s == t){ //如果找到,一路往回返回true.
return true;
}
vector<DirectedGraphNode*> neigh = s->neighbors;
for(int i=0; i<neigh.size(); ++i){
if(visited[neigh[i]] == true) //如果此节点已经访问过,直接跳过。
continue;
visited[neigh[i]] = true; //标记此节点为已访问。
bool flag = hasRoute(graph, neigh[i], t);
if(flag == true) //只有结果为真时,才返回,结果为假,接着循环其他节点。
return flag;
}
return false; //当前相邻节点已经全部访问并且没有找到,返回给上一层结果为false,直到最上层.
}
};
除了深度优先搜索,此题还可以广度优先搜索。
利用队列,保存所有从s开始的路线上的节点,逐个遍历。判断是否出现t节点,直到队列为空。返回false.
从lintcode上的运行时间来说,广度优先比深度优先是要慢上一些的。
代码:
bool hasRoute(vector<DirectedGraphNode*> graph, DirectedGraphNode* s, DirectedGraphNode* t) {
// write your code here
if(graph.empty())
return false;
queue<DirectedGraphNode*> que;
que.push(s);
while(!que.empty()){
DirectedGraphNode* tmp = que.front();
que.pop();
if(tmp == t)
return true;
vector<DirectedGraphNode*> v = tmp->neighbors; //每访问一个节点,就将和此节点相邻的节点push到队列中,
for(int i=0; i<v.size(); ++i){ //可能会有重复节点进入队列,这里没有进行检查。
que.push(v[i]);
}
}
return false;
}