lintcode-图中两个点之间的路线-176
2015-09-19 20:22
253 查看
给出一张有向图,设计一个算法判断两个点
for
and
return
and
return
s与
t之间是否存在路线。如下图
A----->B----->C \ | \ | \ | \ v ->D----->E
for
s = B
and
t = E,
return
truefor
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); } };第二种解法 BFS
/** * 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; } };
相关文章推荐
- hadoop 2.7.1 64位库编译
- 对调数问题
- 如何让UIImageView具有像UIButton一样的点击效果
- [转]php Imagick写文字图片并自动换行
- 内存溢出
- HDU 5456(数位dp)
- 关于JDK的终极环境变量的配置
- Java对象表示方式1:序列化、反序列化和transient关键字的作用
- canvas标签怎么学习好?
- 关于创建子包(package)的问题
- hdu 5461 Largest Point
- SharpDevelop安装与配置
- ja_charity模板研究_contin_1
- CSS声明顺序
- Mysql安装过程中遇到的问题及解决办法
- 第一阶段快结束了。。。。
- 窗口子控件
- JS前端正则表达式学习笔记(转)
- SGML与HTML、XML
- 回收键盘相关方法