- 代码实现:
//图节点
public class MapNode {
public String val;
public List<MapNode> neighbor;//记录周围的点
public int index;
public MapNode(String val, int index) {
this.val = val;
this.index = index;
neighbor = new ArrayList<>();
}
}
public static boolean deepsearch(MapNode start, int target){
return deepSearch(start,target,new HashSet<>());
}
public static boolean deepSearch(MapNode start, int target, Set<MapNode> points){
if(start == null) return false;
if(start.index == target) return true;
points.add(start);
boolean result = false;
for (MapNode node : start.neighbor){//当前节点没有找到,向下递归
if(!points.contains(node)){//找过的点不需要找了
result |= deepSearch(node,target,points);
}
}
return result;
}
测试:
public class Main {
public static void main(String[] args) {
MapNode n1 = new MapNode("1",1);
MapNode n2 = new MapNode("2",2);
MapNode n3 = new MapNode("3",3);
MapNode n4 = new MapNode("4",4);
MapNode n5 = new MapNode("5",5);
MapNode n6 = new MapNode("6",6);
MapNode n7 = new MapNode("7",7);
MapNode n8 = new MapNode("8",8);
MapNode n9 = new MapNode("9",9);
n1.neighbor.add(n2);
n2.neighbor.add(n1);
n1.neighbor.add(n3);
n3.neighbor.add(n1);
n1.neighbor.add(n4);
n4.neighbor.add(n1);
n2.neighbor.add(n5);
n5.neighbor.add(n2);
n1.neighbor.add(n6);
n6.neighbor.add(n1);
n2.neighbor.add(n6);
n6.neighbor.add(n2);
n3.neighbor.add(n7);
n7.neighbor.add(n3);
n4.neighbor.add(n8);
n8.neighbor.add(n4);
n5.neighbor.add(n9);
n9.neighbor.add(n5);
n6.neighbor.add(n9);
n9.neighbor.add(n6);
System.out.println(deepsearch(n1,10));//false
System.out.println(deepsearch(n1,7));//true
}
}