码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] 618 Search Graph Nodes 解题报告

时间:2017-05-14 01:16:38      阅读:247      评论:0      收藏:0      [点我收藏+]

标签:store   target   find   arc   targe   contains   res   lintcode   efi   

Description
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.

Notice
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

5/13/2017

算法班,未经验证

不是很明白label和values的关系

 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         // Write your code here
24         if (graph == null) return ret;
25         UndirectedGraphNode ret = null;
26         Set<UndirectedGraphNode> set = new HashSet<UndirectedGraphNode>();
27 
28         Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
29         queue.offer(node);
30         while (!queue.isEmpty()) {
31             UndirectedGraphNode t = queue.poll();
32             if (values.get(t) == target) {
33                 return t;
34             }
35             for (UndirectedGraphNode n: t.neighbors) {
36                 if (!set.contains(n)) {
37                     set.add(n);
38                     queue.offer(n);
39                 }
40             }
41         }
42         return null;
43     }
44 }

 

[LintCode] 618 Search Graph Nodes 解题报告

标签:store   target   find   arc   targe   contains   res   lintcode   efi   

原文地址:http://www.cnblogs.com/panini/p/6850882.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!