题目描述
对于一个有向图,请实现一个算法,找出两点之间是否存在一条路径。
给定图中的两个结点的指针UndirectedGraphNode* a,UndirectedGraphNode* b(请不要在意数据类型,图是有向图),请返回一个bool,代表两点之间是否存在一条路径(a到b或b到a)。
import java.util.*;
/*
public class UndirectedGraphNode {
int label = 0;
UndirectedGraphNode left = null;
UndirectedGraphNode right = null;
ArrayList<UndirectedGraphNode> neighbors = new ArrayList<UndirectedGraphNode>();
public UndirectedGraphNode(int label) {
this.label = label;
}
}*/
public class Path {
public boolean checkPath(UndirectedGraphNode a, UndirectedGraphNode b) {
return check(a,b)||check(b,a);
}
private boolean check(UndirectedGraphNode a, UndirectedGraphNode b){
if(a == null || b == null){
return false;
}else if(a == b){
return true;
}
LinkedList<UndirectedGraphNode> q=new LinkedList();
ArrayList<UndirectedGraphNode> checkedMap = new ArrayList<UndirectedGraphNode>();
q.add(a);
checkedMap.add(a);
while(!q.isEmpty()){
UndirectedGraphNode node=q.poll();
for(UndirectedGraphNode temp:node.neighbors){
if(!checkedMap.contains(temp)){
if(temp==b){
return true;
}else{
checkedMap.add(temp);
q.add(temp);
}
}
}
}
return false;
}
}