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
            //这里因为是递归每次传入的都是应当前的主节点而不是他的邻居
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值