标签: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