133. Clone Graph

GraphNode {
    int val;
    List<GraphNode> children;
}




public GraphNode copyGraph(GraphNode root){
    Queue<GraphNode> queue = new LinkedList<>();
    HashMap<GraphNode, GraphNode> map = new HashMap<>();
    GraphNode newRoot = new GraphNode(root.val);
    queue.offer(root);
    map.put(root, newRoot);
        
    // bfs
    while(!queue.isEmpty()){
        GraphNode cur = queue.poll();
        // connect the copy with the chilren copy and put the children copy into the queue 
        GraphNode curCopy = map.get(cur);
        // make all the children copy of the cur 
        for(GraphNode child : cur.children){
            if(map.containsKey(child)) continue;
            GraphNode childCopy = new GraphNode(child.val);
            curCopy.children.add(childCopy);
            map.put(child, childCopy);
            queue.offer(child); 
        }
    }
    return newRoot;
}

 

Given the head of a graph, return a deep copy (clone) of the graph. Each node in the graph contains a label (int) and a list (List[UndirectedGraphNode]) of its neighbors. There is an edge between the given node and each of the nodes in its neighbors.


OJ's undirected graph serialization (so you can understand error output):

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


dfs

https://leetcode.com/problems/clone-graph/discuss/42309/Depth-First-Simple-Java-Solution

 

posted on 2018-08-11 03:54  猪猪&#128055;  阅读(120)  评论(0)    收藏  举报

导航