[LintCode] Search Graph Nodes

Given a undirected graph, a node and a target, return the nearest node to given node which value of it is target, return NULL if you can't find.

There is a mapping store the nodes' values in the given parameters.

It's guaranteed there is only one available solution.

Example
2------3  5
      |  | 
      |  |
      |  |
      |  |
      1 --4
Give a node 1, target is 50

there a hash named values which is [3,4,10,50,50], represent:
Value of node 1 is 3
Value of node 2 is 4
Value of node 3 is 10
Value of node 4 is 50
Value of node 5 is 50

Return node 4


 1 /**
 2  * Definition for graph node.
 3  * class UndirectedGraphNode {
 4  *     int label;
 5  *     ArrayList<UndirectedGraphNode> neighbors;
 6  *     UndirectedGraphNode(int x) { 
 7  *         label = x; neighbors = new ArrayList<UndirectedGraphNode>(); 
 8  *     }
 9  * };
10  */
11 public class Solution {
12     /**
13      * @param graph a list of Undirected graph node
14      * @param values a hash mapping, <UndirectedGraphNode, (int)value>
15      * @param node an Undirected graph node
16      * @param target an integer
17      * @return the a node
18      */
19     public UndirectedGraphNode searchNode(ArrayList<UndirectedGraphNode> graph,
20                                           Map<UndirectedGraphNode, Integer> values,
21                                           UndirectedGraphNode node,
22                                           int target) {
23         if(graph == null || graph.size() == 0 || node == null)
24         {
25             return null;
26         }
27         if(values.get(node) == target)
28         {
29             return node;
30         }
31         
32         Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
33         HashSet<UndirectedGraphNode> visited = new HashSet<UndirectedGraphNode>();
34         queue.offer(node);
35         visited.add(node);
36         
37         while(!queue.isEmpty())
38         {
39             UndirectedGraphNode headNode = queue.poll();
40             for(UndirectedGraphNode neighbor : headNode.neighbors)
41             {
42                 if(visited.contains(neighbor))
43                 {
44                    continue; 
45                 }
46                 if(values.get(neighbor) == target)
47                 {
48                     return neighbor;
49                 }
50                 queue.offer(neighbor);
51                 visited.add(neighbor);
52             }
53         }
54         return null;
55     }
56 }


Related Problems

Knight Shortest Path

Binary Tree Level Order Traversal II




原文地址:https://www.cnblogs.com/lz87/p/7496897.html