lintcode618: Search Graph Nodes

别来无恙 提交于 2020-01-16 00:22:37

问题描述

在这里插入图片描述

java实现

// 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: a node
         */
        public UndirectedGraphNode searchNode(ArrayList<UndirectedGraphNode> graph,
                                              Map<UndirectedGraphNode, Integer> values,
                                              UndirectedGraphNode node,
                                              int target) {
            // write your code here
            if (graph == null || node == null || values == null) {
                return null;
            }
            Queue<UndirectedGraphNode> queue = new LinkedList<>();
            Set<UndirectedGraphNode> set = new HashSet<>();

            queue.offer(node);
            set.add(node);

            while (!queue.isEmpty()) {
                UndirectedGraphNode current = queue.poll();
                if (values.get(current) == target) {
                    return current;
                }
                for (UndirectedGraphNode neighbor : current.neighbors) {
                    if (!set.contains(neighbor)) {
                        queue.offer(neighbor);
                        set.add(neighbor);
                    }
                }
            }
            return null;
        }
    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!