一、问题描述
对于一个有向图,请实现一个算法,找出两点之间是否存在一条路径。给定途中的两个节点的指针UndirectedGraphNode* a,UndirectedGraphNode* b(请不要在意数据类型,图是有向图),请返回一个bool,代表两点之间是否存在一条路径(a到b或b到a)。
二、思路分析
有向图的路径查找一般分为深度优先遍历和广度优先遍历,深度优先遍历用堆栈或者递归来实现,广度优先遍历用队列来实现。
如果是采用深度优先遍历,1=>2=>5=>6=>3=>7=>8=>9=>4=>10
如果是采用广度优先遍历,1=>2=>3=>4=>5=>6=>7=>8=>9=>10
为了避免环的出现,无论是广度优先遍历还是深度优先遍历都需要有一个HashSet或者HashMap来记录访问过的节点,避免无限循环
三、代码
1.深度优先遍历(递归)
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) {
if(a==null || b==null)
return false;
HashSet<UndirectedGraphNode> map=new HashSet<UndirectedGraphNode>();
boolean res=checkPathCore(a,b,map);
map.clear();
return res || checkPathCore(b,a,map);
}
private boolean checkPathCore(UndirectedGraphNode a,UndirectedGraphNode b,HashSet<UndirectedGraphNode> map){
if(a==b)
return true;
map.add(a);
for(int i=0;i<a.neighbors.size();i++){
if(!map.contains(a.neighbors.get(i)) && checkPathCore(a.neighbors.get(i), b,map))
return true;
}
return false;
}
}
2.广度优先遍历(队列)
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) {
// write code here
return checkPathCore(a,b) || checkPathCore(b,a);
}
private boolean checkPathCore(UndirectedGraphNode a,UndirectedGraphNode b){
if(a==null || b==null)
return false;
if(a==b)
return true;
Queue<UndirectedGraphNode> queue=new LinkedList<UndirectedGraphNode>();
HashSet<UndirectedGraphNode> map=new HashSet<UndirectedGraphNode>();
queue.add(a);
//map.add(a);
while(queue.peek()!=null){
UndirectedGraphNode temp=queue.poll();
if(temp.neighbors==null)
continue;
for(int i=0;i<temp.neighbors.size();i++){
if(map.contains(temp.neighbors.get(i))){
continue;
}
if(temp.neighbors.get(i)==b)
return true;
queue.add(temp.neighbors.get(i));
//map.add(temp.neighbors.get(i));
//continue;
}
map.add(temp);
}
return false;
}
}