public class Solution {
public boolean hasRoute(ArrayList<DirectedGraphNode> graph,
DirectedGraphNode s, DirectedGraphNode t) {
if (s == t) {
return true;
}
Queue<DirectedGraphNode> queue = new LinkedList<>();
HashSet<DirectedGraphNode> set = new HashSet<>();
queue.offer(s);
set.add(s);
while (!queue.isEmpty()) {
DirectedGraphNode node = queue.poll();
for (DirectedGraphNode neighbor : node.neighbors) {
// t must be a node in the graph, so we can compare if node's neighbor is equal to t
if (neighbor == t) {
return true;
}
if (set.add(neighbor)) {
queue.offer(neighbor);
}
}
}
return false;
}
}
Route Between Two Nodes in Graph
最新推荐文章于 2021-05-08 17:30:11 发布