Search Graph Nodes

public class Solution {
    /*
     * @param graph: a list of Undirected graph node
     * @param values: a hash mapping, <UndirectedGraphNode, (int)value>
     * @param node: an Undirected graph node
     * @param target: An integer
     * @return: a node
     */
		public UndirectedGraphNode searchNode(ArrayList<UndirectedGraphNode> graph,
		                                          Map<UndirectedGraphNode, Integer> values,
		                                          UndirectedGraphNode node,
		                                          int target) {
			Queue<UndirectedGraphNode> queue = new LinkedList<>();
			Set<UndirectedGraphNode> set = new HashSet<>();
			queue.offer(node);
			set.add(node);
			
			while (!queue.isEmpty()) {
				UndirectedGraphNode curNode = queue.poll();
				if (values.get(curNode) == target) return curNode;
				for (UndirectedGraphNode nei : curNode.neighbors) {
					if (!set.contains(nei)) {
						queue.offer(nei);
						set.add(nei);
					}
				}
			}
			return null;
		}
}

最后更新于

这有帮助吗?