LeetCode 19 Clone Graph

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

分析:

广度优先遍历,涉及队列的应用,

节点有没有访问过的标记,HashMap的应用。

/**
 * Definition for undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     List<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
 * };
 */
public class Solution {
    public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
        if(node == null) return null;
        //广度优先遍历的常规技术,利用队列
        Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>();
        //HashMap用来标记节点有没有访问过
        HashMap<UndirectedGraphNode,UndirectedGraphNode> hashMap = new HashMap<UndirectedGraphNode,UndirectedGraphNode>();
        //先把第一个节点放进队列,完成初始化
        queue.add(node);
        UndirectedGraphNode clone = new UndirectedGraphNode(node.label);
        hashMap.put(node, clone);
        //开始遍历
        while(!queue.isEmpty()){
            UndirectedGraphNode curr = queue.remove();
            UndirectedGraphNode currClone = hashMap.get(curr);
            //对于当前节点的邻居
            for(UndirectedGraphNode item : curr.neighbors){
                //如果在hashMap里,说明已经访问过,建立指针关系即可
                if(hashMap.containsKey(item)){
                    currClone.neighbors.add(hashMap.get(item));
                }else{//如果没有在hashMap里,说明没有访问过,除了新建节点并建立指针关系外,
                    //还要再hashMap里放入新对,并将没有访问过的节点入队
                    UndirectedGraphNode newItem = new UndirectedGraphNode(item.label);
                    currClone.neighbors.add(newItem);
                    hashMap.put(item, newItem);
                    queue.add(item);
                }
            }
        }
        return clone;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值