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
         / \
         \_/

原题链接: http://oj.leetcode.com/problems/clone-graph/ 
这道题是LeetCode中为数不多的关于图的题目,不过这道题还是比较基础,就是考察图非常经典的方法:深度优先搜索广度优先搜索。这道题用两种方法都可以解决,因为只是一个图的复制,用哪种遍历方式都可以。具体细节就不多说了,因为两种方法太常见了。这里恰好可以用旧结点和新结点的HashMap来做visited的记录。下面是广度优先搜索的代码: 
  1. public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {  
  2.     if(node==null)  
  3.         return null;  
  4.     LinkedList<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();  
  5.     HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();  
  6.     UndirectedGraphNode copy = new UndirectedGraphNode(node.label);  
  7.     map.put(node,copy);  
  8.     queue.offer(node);  
  9.     while(!queue.isEmpty())  
  10.     {  
  11.         UndirectedGraphNode cur = queue.poll();  
  12.         for(int i=0;i<cur.neighbors.size();i++)  
  13.         {  
  14.             if(!map.containsKey(cur.neighbors.get(i)))  
  15.             {  
  16.                 copy = new UndirectedGraphNode(cur.neighbors.get(i).label);  
  17.                 map.put(cur.neighbors.get(i),copy);  
  18.                 queue.offer(cur.neighbors.get(i));  
  19.             }  
  20.             map.get(cur).neighbors.add(map.get(cur.neighbors.get(i)));  
  21.         }  
  22.     }  
  23.     return map.get(node);  
  24. }  
深度优先搜索的代码如下:
  1. public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {  
  2.     if(node == null)  
  3.         return null;  
  4.     LinkedList<UndirectedGraphNode> stack = new LinkedList<UndirectedGraphNode>();  
  5.     HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();  
  6.     stack.push(node);  
  7.     UndirectedGraphNode copy = new UndirectedGraphNode(node.label);  
  8.     map.put(node,copy);  
  9.     while(!stack.isEmpty())  
  10.     {  
  11.         UndirectedGraphNode cur = stack.pop();  
  12.         for(int i=0;i<cur.neighbors.size();i++)  
  13.         {  
  14.             if(!map.containsKey(cur.neighbors.get(i)))  
  15.             {  
  16.                 copy = new UndirectedGraphNode(cur.neighbors.get(i).label);  
  17.                 map.put(cur.neighbors.get(i),copy);  
  18.                 stack.push(cur.neighbors.get(i));  
  19.             }  
  20.             map.get(cur).neighbors.add(map.get(cur.neighbors.get(i)));  
  21.         }  
  22.     }  
  23.     return map.get(node);  
  24. }  
当然深度优先搜索也可以用递归来实现,代码如下:
  1. public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {  
  2.     if(node == null)  
  3.         return null;  
  4.     HashMap<UndirectedGraphNode, UndirectedGraphNode> map = new HashMap<UndirectedGraphNode, UndirectedGraphNode>();  
  5.     UndirectedGraphNode copy = new UndirectedGraphNode(node.label);  
  6.     map.put(node,copy);  
  7.     helper(node,map);  
  8.     return copy;  
  9. }  
  10. private void helper(UndirectedGraphNode node, HashMap<UndirectedGraphNode, UndirectedGraphNode> map)  
  11. {  
  12.     for(int i=0;i<node.neighbors.size();i++)  
  13.     {   
  14.         UndirectedGraphNode cur = node.neighbors.get(i);  
  15.         if(!map.containsKey(cur))  
  16.         {  
  17.             UndirectedGraphNode copy = new UndirectedGraphNode(cur.label);  
  18.             map.put(cur,copy);  
  19.             helper(cur,map);  
  20.         }  
  21.         map.get(node).neighbors.add(map.get(cur));  
  22.     }  
  23. }  
这
几种方法的时间复杂度都是O(n)(每个结点访问一次),而空间复杂度则是栈或者队列的大小加上HashMap的大小,也不会超过O(n)。图的两种遍历
方式是比较经典的问题了,虽然在面试中出现的不多,但是还是有可能出现的,而且如果出现了就必须做好,所以大家还是得好好掌握哈。
/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
public:
    UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
        if (node == NULL) return NULL;
        
        unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> mapper;
        UndirectedGraphNode *newNode = new UndirectedGraphNode(node->label);
        mapper[node] = newNode;
        queue<UndirectedGraphNode*> q;
        q.push(node);
        
        while (!q.empty()) {
            UndirectedGraphNode *cur = q.front();
            q.pop();
            for (int i = 0; i < cur->neighbors.size(); i++) {
                UndirectedGraphNode *temp = cur->neighbors[i];
                if (mapper.find(temp) == mapper.end()) {
                    mapper[temp] = new UndirectedGraphNode(temp->label);
                    q.push(temp);
                }
                mapper[cur]->neighbors.push_back(mapper[temp]);
            }
        }

        return newNode;        
    }
};

 



posted on 2015-01-08 21:50  风云逸  阅读(102)  评论(0)    收藏  举报