137题 Clone Graph

本文介绍了一种解决方案,如何使用Java实现无向图的深度复制,CloneGraph方法确保新图与原图结构相同,修改新图不影响原图。通过UndirectedGraphNode类,展示了节点的唯一标识和邻居列表的操作,以及如何利用哈希映射和队列来遍历和复制整个图结构。

Clone Graph

Description
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. Nodes are labeled uniquely.

You need to return a deep copied graph, which has the same structure as the original graph, and any changes to the new graph will not have any effect on the original graph

/**
 * Definition for Undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     List<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) {
 *         label = x;
 *         neighbors = new ArrayList<UndirectedGraphNode>();
 *     }
 * }
 */

public class Solution {
    /**
     * @param node: A undirected graph node
     * @return: A undirected graph node
     */
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        // write your code here
        if(node == null){
            return null ;
        }
        ArrayList<UndirectedGraphNode> nodes = getNodes(node) ;
        Map<UndirectedGraphNode,UndirectedGraphNode> mapping = new HashMap<>();
        for(UndirectedGraphNode n : nodes){
            mapping.put(n , new UndirectedGraphNode(n.label));
        }
        for(UndirectedGraphNode n : nodes){
            UndirectedGraphNode newnodes = mapping.get(n) ;
            for(UndirectedGraphNode neighbor : n.neighbors){
                UndirectedGraphNode newneighbors = mapping.get(neighbor) ;
                newnodes.neighbors.add(newneighbors);
            }
        }
        return mapping.get(node); //返回与给定节点具有相同 label 的那个节点.
    }
    public ArrayList getNodes(UndirectedGraphNode node){
        Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
        HashSet<UndirectedGraphNode> set = new HashSet<UndirectedGraphNode>();
        queue.offer(node) ;
        set.add(node) ;
        while(!queue.isEmpty()){
            UndirectedGraphNode head = queue.poll();
            for(UndirectedGraphNode neighbor : head.neighbors){
                if(!set.contains(neighbor)){
                      queue.offer(neighbor);
                      set.add(neighbor) ;
                }
            }
        }
        return new ArrayList<UndirectedGraphNode>(set) ;
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值