给出一张有向图,设计一个算法判断两个点 s 与 t 之间是否存在路线。
您在真实的面试中是否遇到过这个题?
Yes
样例
如下图:
A----->B----->C
\ |
\ |
\ |
\ v
->D----->E
for s = B and t = E, return true
for s = D and t = C, return false
标签 Expand
相关题目 Expand
您在真实的面试中是否遇到过这个题?
Yes
样例
如下图:
A----->B----->C
\ |
\ |
\ |
\ v
->D----->E
for s = B and t = E, return true
for s = D and t = C, return false
标签 Expand
相关题目 Expand
解题思路:
宽度优先搜索
/**
* Definition for Directed graph.
* class DirectedGraphNode {
* int label;
* ArrayList<DirectedGraphNode> neighbors;
* DirectedGraphNode(int x) {
* label = x;
* neighbors = new ArrayList<DirectedGraphNode>();
* }
* };
*/
public class Solution {
/**
* @param graph: A list of Directed graph node
* @param s: the starting Directed graph node
* @param t: the terminal Directed graph node
* @return: a boolean value
*/
public boolean hasRoute(ArrayList<DirectedGraphNode> graph,
DirectedGraphNode s, DirectedGraphNode t) {
// write your code here
if(0==graph.size()||null==graph) return false;
Queue<DirectedGraphNode> curNodes = new LinkedList<DirectedGraphNode>();
curNodes.add(s);
while(null!=curNodes&&curNodes.size()>0){
DirectedGraphNode curNode = curNodes.poll();
if(curNode!=null){
if(curNode==t){
return true;
}else {
ArrayList<DirectedGraphNode> neighbors = curNode.neighbors;
for(DirectedGraphNode node:neighbors){
curNodes.add(node);
}
}
}
}
return false;
}
}