lintcode-图中两个点之间的路线-176
来源:互联网 发布:软件测试工程师难学不 编辑:程序博客网 时间:2024/05/21 14:08
给出一张有向图,设计一个算法判断两个点 s
与 t
之间是否存在路线。
如下图
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); }};
第二种解法 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; }};
0 0
- lintcode-图中两个点之间的路线-176
- LintCode-图中两个点之间的路线
- LintCode:图中两个点之间的路线
- lintcode -- 图中两个点之间的路线
- 图中两个点之间的路线 -LintCode
- lintcode 图中两个点之间的路线 广度优先搜索
- 图中两个点之间的路线
- 图中两个点之间的路线
- 题目:图中两个点之间的路线
- 176.Route Between Two Nodes in Graph-图中两个点之间的路线(中等题)
- 计算蜂窝中两个点之间的距离
- 计算两个坐标点之间的距离
- 计算两个坐标点之间的距离
- ACM2001Java实现两个点之间的距离
- 在百度地图API开发中已知两个点之间的经纬度坐标计算其距离
- 在百度地图API开发中已知两个点之间的经纬度坐标计算其距离
- Altium Designer中测量Gerber文件两个点之间的距离
- cocos2dx中lua计算两个点之间夹角计算
- 最少拦截系统 1257 (动态规划)
- 关于创建子包(package)的问题
- 关于JDK的终极环境变量的配置
- ScrollView内展示ListView显示不完全(只显示一个Item)
- 藏龙卧虎
- lintcode-图中两个点之间的路线-176
- 如何让UIImageView具有像UIButton一样的点击效果
- jspEL的表达式<c:if ne>
- Xcode 7免证书真机调试
- 机房收费文档第一遍总结
- hdu 1503 Advanced Fruits(最长公共子序列的应用)
- css知多少(11)——position
- 把《Effective C++》读薄
- iOS9适配系列教程