leetcode clone graph

题目描述

https://oj.leetcode.com/problems/clone-graph/

思路

第一遍遍历图,在每个节点的neighbors列表的末尾加上一个selfCopyNode,即对该节点的复制节点。

第二遍遍历图,对每个节点的复制节点,让它的每个neighbor都是原节点对应neighbor复制节点。

第三遍遍历图,移除每个节点的selfCopyNode,还原原来的graph,否则无法AC。

代码

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 node;
		Queue<UndirectedGraphNode> q=new LinkedList<UndirectedGraphNode>();
		Set<Integer> visit=new HashSet<Integer>();
		visit.add(node.label);
		q.offer(node);
		while(!q.isEmpty()){
			UndirectedGraphNode pNode=q.poll();
			for(UndirectedGraphNode neighbor:pNode.neighbors){
				if(!visit.contains(neighbor.label)){
					q.offer(neighbor);
					visit.add(neighbor.label);
				}
			}
			UndirectedGraphNode selfCopyNode=new UndirectedGraphNode(pNode.label);
			pNode.neighbors.add(selfCopyNode);
		}
		visit.clear();
		visit.add(node.label);
		q.offer(node);
		while(!q.isEmpty()){
			UndirectedGraphNode pNode=q.poll();
			int size=pNode.neighbors.size();
			UndirectedGraphNode selfCopyNode=pNode.neighbors.get(size-1);
			for(int i=0;i<size-1;i++){
				UndirectedGraphNode neighbor=pNode.neighbors.get(i);
				if(!visit.contains(neighbor.label)){
					q.offer(neighbor);
					visit.add(neighbor.label);
				}
				selfCopyNode.neighbors.add(neighbor.neighbors.get(neighbor.neighbors.size()-1));
			}
		}
		UndirectedGraphNode root=node.neighbors.get(node.neighbors.size()-1);
		visit.clear();
		visit.add(node.label);
		q.offer(node);
		while(!q.isEmpty()){
			UndirectedGraphNode pNode=q.poll();
			int size=pNode.neighbors.size();
			pNode.neighbors.remove(size-1);
			for(int i=0;i<size-1;i++){
				UndirectedGraphNode neighbor=pNode.neighbors.get(i);
				if(!visit.contains(neighbor.label)){
					q.offer(neighbor);
					visit.add(neighbor.label);
				}
			}
		}
		return root;
	}

	public static void main(String[] args) {
		Solution sln = new Solution();
		UndirectedGraphNode node=new UndirectedGraphNode(0);
		node.neighbors.add(node);
		node.neighbors.add(node);
		sln.cloneGraph(node);
	}
}

注意点

处理图为空的情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值