133. 克隆图
给你无向 连通 图中一个节点的引用,请你返回该图的 深拷贝(克隆)。
图中的每个节点都包含它的值 val(int) 和其邻居的列表(list[Node])。
思路
其实就是图的遍历,边遍历边深拷贝即可。
DFS
避免重复遍历图的节点,需要一个哈系表来存储已经遍历的表。
代码
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {
val = 0;
neighbors = vector<Node*>();
}
Node(int _val) {
val = _val;
neighbors = vector<Node*>();
}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/
class Solution {
public:
unordered_map<Node*, Node*> visited;
Node* cloneGraph(Node* node) {
if(node == nullptr) {
return node;
}
if(visited.find(node) != visited.end()) {
return visited[node];
}
Node* cloneNode = new Node(node->val);
visited[node] = cloneNode;
for(auto& neighbor : node->neighbors) {
cloneNode->neighbors.push_back(cloneGraph(neighbor));
}
return visited[node];
}
};
BFS
同理需要一个队列实现bfs。
代码
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> neighbors;
Node() {
val = 0;
neighbors = vector<Node*>();
}
Node(int _val) {
val = _val;
neighbors = vector<Node*>();
}
Node(int _val, vector<Node*> _neighbors) {
val = _val;
neighbors = _neighbors;
}
};
*/
class Solution {
public:
Node* cloneGraph(Node* node) {
if(node == nullptr) {
return node;
}
unordered_map<Node*, Node*> visited;
queue<Node*> q;
q.push(node);
visited[node] = new Node(node->val);
while(!q.empty()) {
Node* tmp = q.front();
q.pop();
for(auto& neighbor : tmp->neighbors) {
if(visited.find(neighbor) == visited.end()) {
visited[neighbor] = new Node(neighbor->val);
q.push(neighbor);
}
//设置邻居
visited[tmp]->neighbors.push_back(visited[neighbor]);
}
}
return visited[node];
}
};