clone Graph的总结之二

今天写clone Graph的的DFS实现方法,这部分采用递归来实现
DFS(Dpeth-first Search)
顾名思义,就是深度搜索,一条路走到黑,再选新的路。
递归写法的DFS伪代码如下:

Input: A graph G and a root v of G
  procedure DFS(G,v):
      label v as discovered
      for all edges from v to w in G.adjacentEdges(v) do
                 if vertex w is not labeled as discovered then
                recursively call DFS(G,w)

用DFS递归实现CloneGraph代码为:

public UndirectedGraphNode cloneGraph(UndirectedGraphNode node){
        if(node == null){
            return node;
        }
        //采用hashmap来保存复制图
        HashMap<UndirectedGraphNode,UndirectedGraphNode> mapping = new HashMap<>();
        //新建一个节点,这里不可以直接引用
        UndirectedGraphNode head = new UndirectedGraphNode(node.label);
        //复制第一个跟节点
        mapping.put(node, head);
        //DFS递归实现复制
        DFS(mapping,node);
        return head;



    }
    public void DFS(HashMap<UndirectedGraphNode,UndirectedGraphNode> mapping,UndirectedGraphNode node){
        if(node == null){
            return;
        }

        for(UndirectedGraphNode aneighbor : node.neighbors){ //从根节点的邻居开始遍历
            if(!mapping.containsKey(aneighbor)){
                UndirectedGraphNode newneighbor = new UndirectedGraphNode(aneighbor.label);
                mapping.put(aneighbor, newneighbor);//复制邻居节点
                //mapping.get(node).neighbors.add(mapping.get(aneighbor));
                //注释掉的这句话不可以写里面是因为如果是{0,0,0}则因0已存在导致直接无法复制邻居节点
            }
            mapping.get(node).neighbors.add(mapping.get(aneighbor));
            //添加邻居关系,注意这里的mapping.get(node)里面不可以为aneighbor,
            //与BFS区分开要,如果BFS使用node则是将所有节点的邻居都复制给第一个head
            //这里因为是递归每次传入的都是应当前的主节点而不是他的邻居
        }
    }
点赞