Saturday, March 7, 2015

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
         / \
         \_/
Solution:
这道题考察对图的遍历和利用HashMap拷贝的方法。
对图的遍历就是两个经典的方法DFS和BFS。BFS经常用Queue实现,DFS经常用递归实现(可改为栈实现)。
拷贝方法是用HashMap,key存原始值,value存copy的值,用DFS,BFS方法遍历帮助拷贝neighbors的值这几种方法的时间复杂度都是O(n)(每个结点访问一次),而空间复杂度则是栈或者队列的大小加上HashMap的大小,也不会超过O(n)
先复习下DFS和BFS。

DFS(Dpeth-first Search)
顾名思义,就是深度搜索,一条路走到黑,再选新的路。
记得上Algorithm的时候,教授举得例子就是说,DFS很像好奇的小孩,你给这个小孩几个盒子套盒子,好奇的小孩肯定会一个盒子打开后继续再在这个盒子里面搜索。
等把这一套盒子都打开完,再打开第二套的。
Wikipedia上的讲解是:“Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. 
One starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible 
along each branch before backtracking.”
通常来说简便的DFS写法是用递归,如果非递归的话就是栈套迭代,思想是一样的。
BFS(Breadth-first Search)
这个就是相对于BFS的另外一种对图的遍历方法,对于一个节点来说先把所有neighbors都检查一遍,再从第一个neighbor开始,循环往复。
由于BFS的这个特质,BFS可以帮助寻找最短路径。
Wikipedia上面对BFS的定义是:
“In graph theory, breadth-first search (BFS) is a strategy for searching in a graph
 when search is limited to essentially two operations: (a) visit and 
inspect a node of a graph; (b) gain access to visit the nodes that 
neighbor the currently visited node. The BFS begins at a root node and 
inspects all the neighboring nodes. Then for each of those neighbor 
nodes in turn, it inspects their neighbor nodes which were unvisited, 
and so on. Compare BFS with the equivalent, but more memory-efficient 
Iterative deepening depth-first search and contrast with depth-first search.”
Solution1:
第一种实现方法是BFS的,就是先将头节点入queue,每一次queue出列一个node,然后检查这个node的所有的neighbors,如果没visited过,就入队,并更新neighbor。然后更新新的neighbor列表。
/**
 * Definition for undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     List neighbors;
 *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); }
 * };
 */
public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if(node == null)
            return null;
        
        //key放原始值, value放copy值
        HashMap map = new HashMap();
        LinkedList queue = new LinkedList();
        UndirectedGraphNode head = new UndirectedGraphNode(node.label);
        map.put(node, head);
        queue.add(node);
        
        while(!queue.isEmpty()) {
            UndirectedGraphNode cur = queue.poll();
            for(UndirectedGraphNode neighbor : cur.neighbors) {  //check each neighbor
                if(!map.containsKey(neighbor)) {  //if not visited,then add to queue
                    queue.add(neighbor);
                    UndirectedGraphNode newNeighbor = new UndirectedGraphNode(neighbor.label);
                    map.put(neighbor, newNeighbor);
                }
                map.get(cur).neighbors.add(map.get(neighbor));
            }
        }
        return head;
    }
}
Solution2.0: DFS的递归操作如下,迭代复制neighbors。
/**
 * Definition for undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     List neighbors;
 *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); }
 * };
 */
public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if(node == null)
            return null;
        
        //key放原始值, value放copy值
        HashMap map = new HashMap();
        UndirectedGraphNode head = new UndirectedGraphNode(node.label);
        map.put(node, head);
        dfs(node, map); //DFS
        return head;

    }
    
    public void dfs(UndirectedGraphNode node, HashMap map) {
        if(node == null)
            return;
        
        for(UndirectedGraphNode neighbor : node.neighbors) {
            if(!map.containsKey(neighbor)) { 
                UndirectedGraphNode newNeighbor = new UndirectedGraphNode(neighbor.label);
                map.put(neighbor, newNeighbor);
                dfs(neighbor, map);  //DFS
            }
            map.get(node).neighbors.add(map.get(neighbor));
        }
    }
}
Solution2.1: DFS的非递归方法,把BFS中的queue换成stack,因为出列方法不一样了,所以遍历的线路就不一样了。
/**
 * Definition for undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     List neighbors;
 *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList(); }
 * };
 */
public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if(node == null)
            return null;
        
        //key放原始值, value放copy值
        HashMap map = new HashMap();
        LinkedList stack = new LinkedList();
        UndirectedGraphNode head = new UndirectedGraphNode(node.label);
        map.put(node, head);
        stack.push(node);
        
        while(!stack.isEmpty()) {
            UndirectedGraphNode cur = stack.pop();
            for(UndirectedGraphNode neighbor : cur.neighbors) {  //check each neighbor
                if(!map.containsKey(neighbor)) {  //if not visited,then push to stack
                    stack.push(neighbor);
                    UndirectedGraphNode newNeighbor = new UndirectedGraphNode(neighbor.label);
                    map.put(neighbor, newNeighbor);
                }
                map.get(cur).neighbors.add(map.get(neighbor));
            }
        }
        return head;
    }
}

No comments:

Post a Comment