克隆一张无向图,图中的每个节点包含一个 label
(标签)和一个 neighbors
(邻接点)列表 。
OJ的无向图序列化:
节点被唯一标记。
我们用 #
作为每个节点的分隔符,用 ,
作为节点标签和邻接点的分隔符。
例如,序列化无向图 {0,1,2#1,2#2,2}
。
该图总共有三个节点, 被两个分隔符 #
分为三部分。
- 第一个节点的标签为
0
,存在从节点0
到节点1
和节点2
的两条边。 - 第二个节点的标签为
1
,存在从节点1
到节点2
的一条边。 - 第三个节点的标签为
2
,存在从节点2
到节点2
(本身) 的一条边,从而形成自环。
我们将图形可视化如下:
1 / / 0 --- 2 / \_/
/**
* Definition for undirected graph.
* class UndirectedGraphNode {
* int label;
* List<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
if(node == null) return null;
HashMap<UndirectedGraphNode,UndirectedGraphNode> hashMap = new HashMap<>();
LinkedList<UndirectedGraphNode> queue = new LinkedList<>();
UndirectedGraphNode head = new UndirectedGraphNode(node.label);
hashMap.put(node,head);
queue.offer(node);
while(!queue.isEmpty()){
UndirectedGraphNode curNode = queue.poll();
for(UndirectedGraphNode neighbor:curNode.neighbors){
if(hashMap.containsKey(neighbor)==false){
queue.offer(neighbor);
UndirectedGraphNode newNeighbor = new UndirectedGraphNode(neighbor.label);
hashMap.put(neighbor,newNeighbor);
}
hashMap.get(curNode).neighbors.add(hashMap.get(neighbor));
}
}
return head;
}
}
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {//DFS
if (node == null) return null;
HashMap<UndirectedGraphNode, UndirectedGraphNode> hashMap = new HashMap<>();
UndirectedGraphNode head = new UndirectedGraphNode(node.label);
hashMap.put(node, head);
DFSSearch(hashMap, node);
return head;
}
private void DFSSearch(HashMap<UndirectedGraphNode, UndirectedGraphNode> hashMap, UndirectedGraphNode node) {
if (node == null) return;
for (UndirectedGraphNode neighbor : node.neighbors) {
if (hashMap.containsKey(neighbor) == false) {
UndirectedGraphNode newNeighbor = new UndirectedGraphNode(neighbor.label);
hashMap.put(neighbor, newNeighbor);
DFSSearch(hashMap, neighbor);
}
hashMap.get(node).neighbors.add(hashMap.get(neighbor));
}
}。
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
map<int,UndirectedGraphNode*> A;
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(!node) return NULL;
UndirectedGraphNode *p = new UndirectedGraphNode(node->label);
A[node->label] = p;
for(auto &x:node->neighbors)
if(!A.count(x->label)) p->neighbors.push_back(cloneGraph(x));
else p->neighbors.push_back(A[x->label]);
return p;
}
};