Leetcode 133: Clone Graph

问题描述

Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors.
在这里插入图片描述

思路

  1. node->nodes 使用dfs遍历图得到所有结点
  2. copy nodes 用hash存储<原来结点,新结点>键值对
  3. copy edges 拷贝边(邻居关系)
  4. 返回新构造图的node对应的新node

java实现

/*
// Definition for a Node.
class Node {
    public int val;
    public List<Node> neighbors;

    public Node() {}

    public Node(int _val,List<Node> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
};
*/
class Solution {
        public Node cloneGraph(Node node) {
            if(node==null)
                return node;

            // step 1 node->nodes 使用dfs遍历图得到所有结点
            ArrayList<Node> nodes=getNodes(node);
            // step 2 copy nodes 用hash存储<原来结点,新结点>键值对
            HashMap<Node,Node> mapping=cloneNodes(nodes);
            // step 3 copy edges 拷贝边(邻居关系)
            cloneNeighbors(nodes,mapping);
            //返回新构造图的node对应的新node
            return mapping.get(node);


        }

        // step 1 node->nodes 使用dfs遍历图得到所有结点
        private ArrayList<Node>  getNodes(Node node){
            Queue<Node> queue=new LinkedList<Node>();
            HashSet<Node> set=new HashSet<>();
            queue.offer(node);
            set.add(node);

            while (!queue.isEmpty()){
                Node head=queue.poll();
                for(Node neighbor : head.neighbors){
                    if(set.contains(neighbor))
                        continue;
                    set.add(neighbor);
                    queue.offer(neighbor);
                }
            }
            return new ArrayList<>(set);
        }

        // step 2 copy nodes 用hash存储<原来结点,新结点>键值对
        private  HashMap<Node,Node> cloneNodes( ArrayList<Node> nodes){
            HashMap<Node,Node> mapping=new HashMap<>();
            for(Node node:nodes)
                mapping.put(node,new Node(node.val));//<原来结点,新结点>
            return mapping;
        }

        // step 3 copy edges 拷贝边(邻居关系)
        private void cloneNeighbors( ArrayList<Node> nodes,HashMap<Node,Node> mapping){
            for(Node node:nodes){
                Node newNode=mapping.get(node);//得到原来结点node对应的新结点newNode
                for(Node neighbor:node.neighbors){
                    Node newNeighbor=mapping.get(neighbor);//<node,neighbor> -><newNode,newNeighbor>
                    newNode.neighbors.add(newNeighbor);//构成邻居
                }
            }
        }
    }
发布了172 篇原创文章 · 获赞 22 · 访问量 2万+

猜你喜欢

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