Leetcode 133 Clone Graph(STL)

本文详细介绍了LeetCode第133题Clone Graph的解决方案,通过使用广度优先搜索策略,实现了一个无向图的深拷贝。具体步骤包括创建新的图节点并映射原有节点的关系。

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

题目连接:Leetcode 133 Clone Graph

解题思路:对每个结点用new方法新建一个一样的结点,并且将对应的label和新节点指针的对应关系保存在Map中,每次遍历一个结点是,对应在节点的neighbors中放入对应新结点的指针。

/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */
class Solution {
	public:
		UndirectedGraphNode* getNode(int label, map<int, UndirectedGraphNode*>& graph) {
			if (graph.find(label) == graph.end()) {
				UndirectedGraphNode* tmp = new UndirectedGraphNode(label);
				graph[label] = tmp;
			}
			return graph[label];
		}

		UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
			if (node == NULL) return NULL;
			set<int> visit;
			map<int, UndirectedGraphNode*> graph;

			queue<UndirectedGraphNode*> que;
			que.push(node);
			visit.insert(node->label);

			while (!que.empty()) {
				UndirectedGraphNode* oldNode = que.front();
				que.pop();

				UndirectedGraphNode* newNode = getNode(oldNode->label, graph);
				for (int i = 0; i < oldNode->neighbors.size(); i++) {
					UndirectedGraphNode* tmp = oldNode->neighbors[i];
					newNode->neighbors.push_back(getNode(tmp->label, graph));

					if (visit.count(tmp->label)) continue;
					visit.insert(tmp->label);
					que.push(tmp);
				}
			}
			return graph[node->label];
		}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值