题目描述
题目链接:133. Clone Graph
Given a reference of a node in a connected undirected graph.
Return a deep copy (clone) of the graph.
Each node in the graph contains a value (
int
) and a list (List[Node]
) of its neighbors.
class Node {
public int val;
public List<Node> neighbors;
}
例子
见上方链接。
Constraints
- The number of nodes in the graph is in the range
[0, 100]
.1 <= Node.val <= 100
Node.val
is unique for each node.- There are no repeated edges and no self-loops in the graph.
- The Graph is connected and all nodes can be visited starting from the given node.
解题思路
用广度优先搜索进行原图的遍历,遍历过程中用哈希表来维护两个图中对应的节点。遇到不在哈希表中的节点时则新建节点,在遍历邻居过程中完成新图中的节点链接关系。代码如下:
#include <queue>
#include <unordered_map>
#include <unordered_set>
class Solution {
public:
Node* cloneGraph(Node* node) {
if (node == nullptr) {
return nullptr;
}
Node* ret = new Node(node->val);
std::unordered_map<Node*, Node*> hmap;
hmap[node] = ret;
std::unordered_set<Node*> visited{node};
// bfs
std::queue<Node*> current_level;
current_level.push(node);
while (!current_level.empty()) {
std::queue<Node*> next_level;
while (!current_level.empty()) {
Node* n = current_level.front();
current_level.pop();
for (auto nei : n->neighbors) {
if (hmap.find(nei) == hmap.end()) {
Node* copy = new Node(nei->val);
hmap[nei] = copy;
}
hmap[n]->neighbors.push_back(hmap[nei]);
if (visited.count(nei) == 0) {
next_level.push(nei);
visited.insert(nei);
}
}
}
std::swap(next_level, current_level);
}
return ret;
}
};
- 时间复杂度:
O(|V|+|E|)
- 空间复杂度:
O(|V|+|E|)
GitHub 代码同步地址: 133.CloneGraph.cpp
其他题目: GitHub: Leetcode-C++-Solution 博客: Leetcode-Solutions