思路:建立一个hash表,原节点与新建立的节点建立对应的关系,然后DFS遍历图也行, BFS遍历图也行。
方法一:
BFS
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node == null)
return node;
HashMap<UndirectedGraphNode, UndirectedGraphNode> hm = new HashMap<>();
LinkedList<UndirectedGraphNode> queue = new LinkedList<>();
UndirectedGraphNode head = new UndirectedGraphNode(node.label);
hm.put(node, head);
queue.add(node);
while(!queue.isEmpty())
{
UndirectedGraphNode curnode = queue.poll();
for(UndirectedGraphNode neigh : curnode.neighbors)
{
if(!hm.containsKey(neigh))
{
queue.add(neigh);
UndirectedGraphNode neighbor = new UndirectedGraphNode(neigh.label);
hm.put(neigh, neighbor);
}
hm.get(curnode).neighbors.add(hm.get(neigh));
}
}
return head;
}
}
DFS
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node == null)
return node;
HashMap<UndirectedGraphNode, UndirectedGraphNode> hm = new HashMap<>();
UndirectedGraphNode head = new UndirectedGraphNode(node.label);
hm.put(node, head);
Dfs(hm, node);
return head;
}
public void Dfs(HashMap<UndirectedGraphNode, UndirectedGraphNode> hm, UndirectedGraphNode node){
if(node == null)
return;
for(UndirectedGraphNode neigh : node.neighbors)
{
if(!hm.containsKey(neigh))
{
UndirectedGraphNode neighbor = new UndirectedGraphNode(neigh.label);
hm.put(neigh, neighbor);
Dfs(hm, neigh);
}
hm.get(node).neighbors.add(hm.get(neigh));
}
}
}
用栈 java/cpp
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node == null)
return null;
HashMap<UndirectedGraphNode, UndirectedGraphNode> hm = new HashMap<>();
UndirectedGraphNode head = new UndirectedGraphNode(node.label);
hm.put(node, head);
LinkedList<UndirectedGraphNode> stack = new LinkedList<>();
stack.push(node);
while(!stack.isEmpty())
{
UndirectedGraphNode curnode = stack.pop();
for(UndirectedGraphNode neigh : curnode.neighbors)
{
if(!hm.containsKey(neigh))
{
stack.push(neigh);
UndirectedGraphNode neighbor = new UndirectedGraphNode(neigh.label);
hm.put(neigh, neighbor);
}
hm.get(curnode).neighbors.add(hm.get(neigh));
}
}
return head;
}
}
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(node == nullptr) return node;
unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> hm;
stack<UndirectedGraphNode*> stack;
stack.push(node);
hm[node] = new UndirectedGraphNode(node->label);
while(!stack.empty())
{
UndirectedGraphNode *p1 = stack.top(), *p2 = hm[p1];
stack.pop();
for(int i = 0; i < p1->neighbors.size(); i++)
{
UndirectedGraphNode *neigh = p1->neighbors[i];
if(hm.count(neigh))
p2->neighbors.push_back(hm[neigh]);
else
{
UndirectedGraphNode *temp = new UndirectedGraphNode(neigh->label);
p2->neighbors.push_back(temp);
hm[neigh] = temp;
stack.push(neigh);
}
}
}
return hm[node];
}
};