【题目描述】
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/