clone-graph[克隆无向图]

题目描述

Clone an undirected graph. Each node in the graph contains alabeland a list of itsneighbors.
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use#as a separator for each node, and,as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph{0,1,2# 1,2# 2,2}.
The graph has a total of three nodes, and therefore contains three parts as separated by#.
First node is labeled as0. Connect node0to both nodes1and2.
Second node is labeled as1. Connect node1to node2.
Third node is labeled as2. Connect node2to node2(itself), thus forming a self-cycle.
Visually, the graph looks like the following:

graph

  • 思路
    给定一个无向图,克隆一个一模一样的返回。
    定义一个map存储被克隆的节点和克隆的节点,当不存在克隆的节点时进行克隆操作,否则直接返回。克隆时要把该节点包含的子元素全部克隆出来。
/**
 * Definition for undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     ArrayList neighbors;
 *     UndirectedGraphNode(int x) { 
           label = x; 
           neighbors = new ArrayList(); 
       }
 * };
 */
import java.util.*;
public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if(node == null)
            return node;
        
        //存储克隆的每个节点的信息
        Map map = 
            new HashMap();
        
        return clone(node, map);
    }
    
    public UndirectedGraphNode clone(UndirectedGraphNode node,
        Map map){
        if(node == null)
            return node;
        
        if(map.containsKey(node))
            return map.get(node);
        
        UndirectedGraphNode newNode = new UndirectedGraphNode(node.label);
        map.put(node, newNode); //放在循环前面,否则由于后面的操作会出现访问不到的情况
        for(UndirectedGraphNode n : node.neighbors){
            newNode.neighbors.add(clone(n, map));
        }
        
        return newNode;
    }
}

你可能感兴趣的:(clone-graph[克隆无向图])