1. 程式人生 > >【LeetCode】Clone Graph 解題報告

【LeetCode】Clone Graph 解題報告

【題目】

Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.


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 #.

  1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
  2. Second node is labeled as 1. Connect node 1 to node 2.
  3. Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.

Visually, the graph looks like the following:

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

【思路】

這道題主要是資料結構的應用吧,用一個佇列存放圖中還未被訪問的結點,用一個map存放克隆的新結點。對於佇列中的結點,訪問其鄰居,如果該鄰居已經被克隆,那麼只需維護克隆結點之間的鄰居關係即可,如果該鄰居尚未被克隆,那麼需要new一個新的結點作為它的克隆,並維護克隆後的鄰居關係。

【Java程式碼】

/**
 * Definition for undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     List<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
 * };
 */
public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if (node == null) return null;
        
        UndirectedGraphNode clone = new UndirectedGraphNode(node.label);
        
        //用一個Map來儲存已經克隆的新結點
        HashMap<Integer, UndirectedGraphNode> map = new HashMap<Integer, UndirectedGraphNode>();
        map.put(node.label, clone);
        
        //用一個佇列來儲存沒有訪問過的結點
        LinkedList<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
        queue.add(node);
        
        while (!queue.isEmpty()) {
            UndirectedGraphNode originalnode = queue.remove();
            UndirectedGraphNode clonenode = map.get(originalnode.label);
            
            for (int i = 0; i < originalnode.neighbors.size(); i++) {
                UndirectedGraphNode neighbor = originalnode.neighbors.get(i);
                
                //如果該鄰居結點已被克隆
                if (map.get(neighbor.label) != null) {
                    clonenode.neighbors.add(map.get(neighbor.label));
                    continue;
                }
                
                //把該鄰居放入queue中
                queue.add(neighbor);
                
                //克隆該鄰居結點
                UndirectedGraphNode newnode = new UndirectedGraphNode(neighbor.label);
                
                //把新結點放入map中
                map.put(neighbor.label, newnode);
                
                //把新結點加入鄰居集中
                clonenode.neighbors.add(newnode);
            }
        }
        
        return clone;
    }
}