137.克隆圖

描述

克隆一張無(wú)向圖,圖中的每個(gè)節(jié)點(diǎn)包含一個(gè) label 和一個(gè)列表 neighbors。數(shù)據(jù)中如何表示一個(gè)無(wú)向圖?http://www.lintcode.com/help/graph/你的程序需要返回一個(gè)經(jīng)過(guò)深度拷貝的新圖。這個(gè)新圖和原圖具有同樣的結(jié)構(gòu),并且對(duì)新圖的任何改動(dòng)不會(huì)對(duì)原圖造成任何影響。

樣例

比如,序列化圖 {0,1,2#1,2#2,2} 共有三個(gè)節(jié)點(diǎn), 因此包含兩個(gè)個(gè)分隔符#。

第一個(gè)節(jié)點(diǎn)label為0,存在邊從節(jié)點(diǎn)0鏈接到節(jié)點(diǎn)1和節(jié)點(diǎn)2
第二個(gè)節(jié)點(diǎn)label為1,存在邊從節(jié)點(diǎn)1連接到節(jié)點(diǎn)2
第三個(gè)節(jié)點(diǎn)label為2,存在邊從節(jié)點(diǎn)2連接到節(jié)點(diǎn)2(本身),從而形成自環(huán)。
我們能看到如下的圖:

   1
  / \
 /   \
0 --- 2
     / \
     \_/

代碼

  1. 3steps
/**
 * Definition for undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     ArrayList<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) {
        if (node == null) {
            return node;
        }

        // use bfs algorithm to traverse the graph and get all nodes.
        ArrayList<UndirectedGraphNode> nodes = getNodes(node);
        
        // copy nodes, store the old->new mapping information in a hash map
        HashMap<UndirectedGraphNode, UndirectedGraphNode> mapping = new HashMap<>();
        for (UndirectedGraphNode n : nodes) {
            // 創(chuàng)建hashmap將原圖和新圖之間結(jié)點(diǎn)對(duì)應(yīng)關(guān)系存在hashmap中
            mapping.put(n, new UndirectedGraphNode(n.label));    
            
        }
        
        // copy neighbors(edges)
        for (UndirectedGraphNode n : nodes) {
            // 復(fù)制的新的結(jié)點(diǎn),不能寫(xiě)newNode = n這樣復(fù)制的是引用,我們需要的是deep copy
            UndirectedGraphNode newNode = mapping.get(n); 
            // neighbors是定義好的存儲(chǔ)整型下標(biāo)的數(shù)組     
            for (UndirectedGraphNode neighbor : n.neighbors) { 
                // 復(fù)制相鄰結(jié)點(diǎn),復(fù)制相鄰結(jié)點(diǎn)和復(fù)制的結(jié)點(diǎn)建立邊的關(guān)系          
                UndirectedGraphNode newNeighbor = mapping.get(neighbor);     
                newNode.neighbors.add(newNeighbor);        
            }
        }

        // 從輸入的結(jié)點(diǎn)開(kāi)始逐漸返回圖中每個(gè)結(jié)點(diǎn)對(duì)應(yīng)的信息
        return mapping.get(node);                      
    }
    
    // 用bfs由點(diǎn)到面得到所有結(jié)點(diǎn)信息,返回一個(gè)包含所有結(jié)點(diǎn)的數(shù)組
    private ArrayList<UndirectedGraphNode> getNodes(UndirectedGraphNode node) {
        Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
         // HashSet不允許有相同元素,如果b已是集合中元素,再執(zhí)行set.add(b)無(wú)效
        HashSet<UndirectedGraphNode> set = new HashSet<>();          
        
        queue.offer(node);
        set.add(node);
        // bfs利用隊(duì)列來(lái)控制遍歷圖中結(jié)點(diǎn)的順序
        while (!queue.isEmpty()) {
            UndirectedGraphNode head = queue.poll();
            for (UndirectedGraphNode neighbor : head.neighbors) {
                if(!set.contains(neighbor)){
                    set.add(neighbor);
                    queue.offer(neighbor);
                }
            }
        }

        // 所有結(jié)點(diǎn)都已添加到 set,此處用深度拷貝是因?yàn)橥膺呉肁rrayList,而此處是hashset
        return new ArrayList<UndirectedGraphNode>(set);
    }
}
  1. two steps
/**
 * Definition for undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     ArrayList<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
 * };
 */
public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if (node == null) {
            return null;
        }

        ArrayList<UndirectedGraphNode> nodes = new ArrayList<UndirectedGraphNode>();
        HashMap<UndirectedGraphNode, UndirectedGraphNode> map
            = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();

        // clone nodes    
        nodes.add(node);
        map.put(node, new UndirectedGraphNode(node.label));

        int start = 0;
        while (start < nodes.size()) {
            UndirectedGraphNode head = nodes.get(start++);
            for (int i = 0; i < head.neighbors.size(); i++) {
                UndirectedGraphNode neighbor = head.neighbors.get(i);
                if (!map.containsKey(neighbor)) {
                    map.put(neighbor, new UndirectedGraphNode(neighbor.label));
                    nodes.add(neighbor);
                }
            }
        }

        // clone neighbors
        for (int i = 0; i < nodes.size(); i++) {
            UndirectedGraphNode newNode = map.get(nodes.get(i));
            for (int j = 0; j < nodes.get(i).neighbors.size(); j++) {
                newNode.neighbors.add(map.get(nodes.get(i).neighbors.get(j)));
            }
        }

        return map.get(node);
    }
}
  1. Non-Recursion DFS
/**
 * Definition for undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     ArrayList<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
 * };
 */
class StackElement {
    public UndirectedGraphNode node;
    public int neighborIndex;
    public StackElement(UndirectedGraphNode node, int neighborIndex) {
        this.node = node;
        this.neighborIndex = neighborIndex;
    }
}

public class Solution {
    /**
     * @param node: A undirected graph node
     * @return: A undirected graph node
     */
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if (node == null) {
            return node;
        }

        // use dfs algorithm to traverse the graph and get all nodes.
        ArrayList<UndirectedGraphNode> nodes = getNodes(node);
        
        // copy nodes, store the old->new mapping information in a hash map
        HashMap<UndirectedGraphNode, UndirectedGraphNode> mapping = new HashMap<>();
        for (UndirectedGraphNode n : nodes) {
            mapping.put(n, new UndirectedGraphNode(n.label));
        }
        
        // copy neighbors(edges)
        for (UndirectedGraphNode n : nodes) {
            UndirectedGraphNode newNode = mapping.get(n);
            for (UndirectedGraphNode neighbor : n.neighbors) {
                UndirectedGraphNode newNeighbor = mapping.get(neighbor);
                newNode.neighbors.add(newNeighbor);
            }
        }
        
        return mapping.get(node);
    }
    
    private ArrayList<UndirectedGraphNode> getNodes(UndirectedGraphNode node) {
        Stack<StackElement> stack = new Stack<StackElement>();
        HashSet<UndirectedGraphNode> set = new HashSet<>();
        stack.push(new StackElement(node, -1));
        set.add(node);
        
        while (!stack.isEmpty()) {
            StackElement current = stack.peek();
            current.neighborIndex++;
            // there is no more neighbor to traverse for the current node
            if (current.neighborIndex == current.node.neighbors.size()) {
                stack.pop();
                continue;
            }
            
            UndirectedGraphNode neighbor = current.node.neighbors.get(
                current.neighborIndex
            );
            // check if we visited this neighbor before
            if (set.contains(neighbor)) {
                continue;
            }
            
            stack.push(new StackElement(neighbor, -1));
            set.add(neighbor);
        }
        
        return new ArrayList<UndirectedGraphNode>(set);
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,688評(píng)論 19 139
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,318評(píng)論 25 708
  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問(wèn)題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,931評(píng)論 0 33
  • 原題 克隆一張無(wú)向圖,圖中的每個(gè)節(jié)點(diǎn)包含一個(gè) label 和一個(gè)表 neighbors。你的程序需要返回一個(gè)經(jīng)過(guò)深...
    Jason_Yuan閱讀 1,724評(píng)論 0 0
  • 1 序 2016年6月25日夜,帝都,天下著大雨,拖著行李箱和同學(xué)在校門(mén)口照了最后一張合照,搬離寢室打車(chē)去了提前租...
    RichardJieChen閱讀 5,388評(píng)論 0 12

友情鏈接更多精彩內(nèi)容