# lintcode-图中两个点之间的路线-176

A----->B----->C
\     |
\    |
\   |
\  v
->D----->E


for s = B and t = E, return true

for s = D and t = C, return false

第一种解法 DFS

/**
* Definition for Directed graph.
* struct DirectedGraphNode {
*     int label;
*     vector<DirectedGraphNode *> neighbors;
*     DirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:

map<DirectedGraphNode*,bool> vis;

bool dfs(DirectedGraphNode* s,DirectedGraphNode* t){
if(s==t)
return true;

for(auto e:s->neighbors){
if(vis[e])
continue;
vis[e]=true;
if(dfs(e,t))
return true;
}
return false;
}
bool hasRoute(vector<DirectedGraphNode*> graph,
DirectedGraphNode* s, DirectedGraphNode* t) {
if(graph.empty())
return false;
return dfs(s,t);
}
};


/**
* Definition for Directed graph.
* struct DirectedGraphNode {
*     int label;
*     vector<DirectedGraphNode *> neighbors;
*     DirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:

bool hasRoute(vector<DirectedGraphNode*> graph,
DirectedGraphNode* s, DirectedGraphNode* t) {

queue<DirectedGraphNode*> que;
map<DirectedGraphNode*,bool>  vis;
que.push(s);
vis[s]=true;
while(!que.empty()){
int len=que.size();
while(len--){
DirectedGraphNode* cur=que.front();
if(cur==t)
return true;
que.pop();
for(auto e:cur->neighbors){
if(vis[e])
continue;
que.push(e);
vis[e]=true;
}
}
}
return false;
}
};


• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120