Route Between Two Nodes in Graph

来源:互联网 发布:山东理工大学网络教育 编辑:程序博客网 时间:2024/05/23 15:03
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;    }}

0 0
原创粉丝点击