Clone Graph

Clone Graph

问题:

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

思路:

  dfs 或者 bfs

我的代码1:(dfs)

public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if(node == null) return null;
        HashMap<UndirectedGraphNode,UndirectedGraphNode> hm = new HashMap<UndirectedGraphNode,UndirectedGraphNode>();
        return helper(node, hm);
    }
    public UndirectedGraphNode helper(UndirectedGraphNode node, HashMap<UndirectedGraphNode,UndirectedGraphNode> hm)
    {
        UndirectedGraphNode rst = hm.get(node);
        if(rst == null)
        {
            rst = new UndirectedGraphNode(node.label);
            hm.put(node,rst);
        }
        List<UndirectedGraphNode> original = node.neighbors;
        List<UndirectedGraphNode> newNeighbors = new ArrayList<UndirectedGraphNode>();
        for(UndirectedGraphNode tmp : original)
        {
            if(hm.containsKey(tmp))
            {
                newNeighbors.add(hm.get(tmp));
            }
            else
            {
                UndirectedGraphNode ugn = new UndirectedGraphNode(tmp.label);
                hm.put(tmp, ugn);
                newNeighbors.add(ugn);
                helper(tmp, hm);
            }
        }
        rst.neighbors = newNeighbors;
        return rst;
    }
}
View Code

我的代码2:(bfs)

public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if(node == null) return null;
        HashMap<UndirectedGraphNode,UndirectedGraphNode> hm = new HashMap<UndirectedGraphNode,UndirectedGraphNode>();
        Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
        queue.offer(node);
        UndirectedGraphNode rst = new UndirectedGraphNode(node.label);
        hm.put(node, rst);
        while(!queue.isEmpty())
        {
            UndirectedGraphNode first = queue.poll();
            UndirectedGraphNode ugn = hm.get(first);
            for(UndirectedGraphNode tmp : first.neighbors)
            {
                if(!hm.containsKey(tmp))
                {
                    UndirectedGraphNode newNode = new UndirectedGraphNode(tmp.label);
                    hm.put(tmp,newNode);
                    queue.offer(tmp);
                }
                ugn.neighbors.add(hm.get(tmp));
            }
        }
        return rst;
    }
}
View Code

学习之处:

  • 无论是DFS和BFS写的过程中都出现了死循环的问题,纠结而言是因为对于节点1 有邻居2,3 HashMap里面便有了(1,**)(2,**),(3,**),对于节点2 有邻居2 则我们不需要进一步的访问(进一步的访问是指对于BFS加入到Queue中,对于DFS是下一步的递归),仅仅需要加入到Neighbor中就可以了。
原文地址:https://www.cnblogs.com/sunshisonghit/p/4342067.html