sweet1cris

Untitled

Feb 9th, 2018
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1.  
  2. /**
  3.  * Definition for graph node.
  4.  * class GraphNode {
  5.  *     int label;
  6.  *     ArrayList<UndirectedGraphNode> neighbors;
  7.  *     UndirectedGraphNode(int x) {
  8.  *         label = x; neighbors = new ArrayList<UndirectedGraphNode>();
  9.  *     }
  10.  * };
  11.  */
  12. public class Solution {
  13.     /**
  14.      * @param graph a list of Undirected graph node
  15.      * @param values a hash mapping, <UndirectedGraphNode, (int)value>
  16.      * @param node an Undirected graph node
  17.      * @param target an integer
  18.      * @return the a node
  19.      */
  20.     public UndirectedGraphNode searchNode(ArrayList<UndirectedGraphNode> graph,
  21.                                           Map<UndirectedGraphNode, Integer> values,
  22.                                           UndirectedGraphNode node,
  23.                                           int target) {
  24.         // Write your code here
  25.         Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
  26.         Set<UndirectedGraphNode> hash = new HashSet<UndirectedGraphNode>();
  27.  
  28.         queue.offer(node);
  29.         hash.add(node);
  30.  
  31.         while (!queue.isEmpty()) {
  32.             UndirectedGraphNode head = queue.poll();
  33.             if (values.get(head) == target) {
  34.                 return head;
  35.             }
  36.             for (UndirectedGraphNode nei : head.neighbors) {
  37.                 if (!hash.contains(nei)){
  38.                     queue.offer(nei);
  39.                     hash.add(nei);
  40.                 }
  41.             }
  42.         }
  43.         return null;
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment