Search Graph Nodes

Note:

BSF: if it needs to check the value, should check it when it is coming from Queue. The logic is most clear to do it there. This question is to ask the first node, we don't need to use level. But if it is asking for all the closest nodes, we need to add level in BSF.

/**
 * Definition for graph node.
 * class UndirectedGraphNode {
 *     int label;
 *     ArrayList<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) { 
 *         label = x; neighbors = new ArrayList<UndirectedGraphNode>(); 
 *     }
 * };
 */
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 the a node
     */
    public UndirectedGraphNode searchNode(ArrayList<UndirectedGraphNode> graph,
                                          Map<UndirectedGraphNode, Integer> values,
                                          UndirectedGraphNode node,
                                          int target) {
        // Write your code here
        if (graph == null || graph.size() == 0 || node == null) {
            return null;
        }
        
        Queue<UndirectedGraphNode> q = new LinkedList<UndirectedGraphNode>();
        q.offer(node);
        HashSet<UndirectedGraphNode> set = new HashSet<UndirectedGraphNode>();
        set.add(node);
        while (!q.isEmpty()) {
            UndirectedGraphNode cur = q.poll();
            if (values.get(cur) == target) {
                return cur;
            }
            for (UndirectedGraphNode neighbor : cur.neighbors) {
                if (!set.contains(neighbor)) {
                    q.offer(neighbor);
                    set.add(neighbor);
                }
            }
        }
        return  null;
    }
}

 

posted on 2017-06-14 06:06  codingEskimo  阅读(177)  评论(0编辑  收藏  举报

导航