對於一個有向圖,請實現一個算法,找出兩點之間是否存在一條路徑。給定圖中的兩個結點的指針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 { ArrayList<UndirectedGraphNode> nodeList = new ArrayList<UndirectedGraphNode>(); boolean hasLine = false; public boolean checkPath(UndirectedGraphNode a, UndirectedGraphNode b) { return hasPath(a, b) || hasPath(b, a); } public boolean hasPath(UndirectedGraphNode a, UndirectedGraphNode b){ if(a == b || hasLine){ hasLine = true; return true; }else{ if(!nodeList.contains(a)){ nodeList.add(a); }else{ return false; } } for(int i = 0; i < a.neighbors.size(); i++){ hasPath(a.neighbors.get(i), b); } return hasLine; } }