leetcode之Clone Graph

本文介绍了一种使用深度优先搜索(DFS)和哈希表实现的无向图深度复制方法。通过递归地复制每个节点及其邻居,同时利用哈希表避免重复创建已存在的节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题如下:

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


OJ's undirected graph serialization:

Nodes are labeled uniquely.

We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.

As an example, consider the serialized graph {0,1,2#1,2#2,2}.

The graph has a total of three nodes, and therefore contains three parts as separated by #.

  1. First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
  2. Second node is labeled as 1. Connect node 1 to node 2.
  3. Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.

Visually, the graph looks like the following:

       1
      / \
     /   \
    0 --- 2
         / \
         \_/
这道题看起来挺复杂的,仍是一个深度复制的问题,问题的关键是在复制一个节点时需要判断其邻居是否已被创建,在此可以采用深度优先搜索DFS,利用unordered_map 来保存已经创建的节点,其中key为节点的label,value为节点,在复制节点时首先判断节点是否为空,为空直接返回空节点(此条件处理一个节点都没有的情况),如果节点在map中,则直接返回map中的节点,否则创建新节点,并将新节点加入map中,接下来按照原节点的neighbor依次递归复制新节点的neighbor,最后返回当前节点。

UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
		unordered_map<int,UndirectedGraphNode*>mp;
		return clone(node,mp);
	}
	UndirectedGraphNode *clone(UndirectedGraphNode *node,unordered_map<int,UndirectedGraphNode *>&mp){
		if(node == NULL)
			return node;
		if(mp.find(node->label) != mp.end())
			return mp[node->label];
		UndirectedGraphNode *nNode = new UndirectedGraphNode(node->label);
		mp[nNode->label] = nNode;     //
		for(int i = 0; i < node->neighbors.size(); i++){
			nNode->neighbors.push_back(clone(node->neighbors[i],mp));
		}		
		return nNode;

	}
这里用到了unordered_map,它是一个无序的map,其底层实现基于hash算法,所以其查询速度很快,另外,在创建新节点后及时将节点存入了map中,然后才创建其neighbor,我现在有点儿疑惑的是假如只有一个节点,且其neighbor为其自身,这是怎样创建的呢?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值