Lintcode176 Route Between Two Nodes in Graph solution 题解

来源:互联网 发布:三砖淘宝店铺 编辑:程序博客网 时间:2024/06/05 04:02

【题目描述】

Given a directed graph, design an algorithm to find out whether there is a route between two nodes.

给出一张有向图,设计一个算法判断两个点s与t之间是否存在路线。

【题目链接】

www.lintcode.com/en/problem/route-between-two-nodes-in-graph/

【题目解析】

检测图中两点是否通路,用DFS或者BFS均可,注意检查是否有环。

这里使用哈希表记录节点是否被处理较为方便。深搜时以起点出发,递归处理其邻居节点,需要注意的是处理邻居节点的循环时不是直接 return, 而只在找到路径为真时才返回 true, 否则会过早返回 false 而忽略后续可能满足条件的路径。

【参考答案】

www.jiuzhang.com/solutions/route-between-two-nodes-in-graph/

阅读全文
0 0