lintcode618: Search Graph Nodes

问题描述

在这里插入图片描述

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;
        }
    }
发布了184 篇原创文章 · 获赞 22 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_44135282/article/details/103981468