Clone an undirected graph. Each node in the graph contains a label
and a list of its neighbors
.
Nodes are labeled uniquely.
We use#
as a separator for each node, and
,
as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph {0,1,2#1,2#2,2}
.
The graph has a total of three nodes, and therefore contains three parts as separated by #
.
0
. Connect node 0
to both nodes 1
and 2
.1
. Connect node 1
to node 2
.2
. Connect node 2
to node 2
(itself), thus forming a self-cycle.Visually, the graph looks like the following:
1 / \ / \ 0 --- 2 / \ \_/
BFS,用hash来存储新的图和旧图的一一对应关系的点,采用BFS搜索。然后对每一个点存相邻点。
/** * Definition for undirected graph. * struct UndirectedGraphNode { * int label; * vector<UndirectedGraphNode *> neighbors; * UndirectedGraphNode(int x) : label(x) {}; * }; */ class Solution { public: UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) { unordered_map<UndirectedGraphNode * ,UndirectedGraphNode *> NodeMap; //和克隆图之间的Map这样可以一次遍历完 queue<UndirectedGraphNode *> Qq; if(node == NULL) return node; Qq.push(node); while(!Qq.empty()){ UndirectedGraphNode *top = Qq.front(); Qq.pop(); if(NodeMap.count(top)==0){//没有节点 UndirectedGraphNode * Temp = new UndirectedGraphNode(top->label); NodeMap[top] = Temp; } //保存相邻节点 for(auto it = top->neighbors.begin(); it!=top->neighbors.end(); ++it){ UndirectedGraphNode *adj = *it; if(NodeMap.count(adj)==0){//没有该节点,创建节点,同时间也避免了环,之前遍历过的节点不会再遍历 UndirectedGraphNode *Temp = new UndirectedGraphNode(adj->label); NodeMap[adj] = Temp; Qq.push(adj); } NodeMap[top]->neighbors.push_back(NodeMap[adj]); //给定字节点所有链接节点,如果有环也会保留,因为没有入队列 } } return NodeMap[node]; } };