题目描述:
Clone an undirected graph. Each node in the graph contains alabel
and
a list of its neighbors
.
How we serialize an undirected graph:
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 #
.
- First node is labeled as
0
. Connect node0
to both nodes1
and2
. - Second node is labeled as
1
. Connect node1
to node2
. - Third node is labeled as
2
. Connect node2
to node2
(itself), thus forming a self-cycle.
Visually, the graph looks like the following:
1
/ \
/ \
0 --- 2
/ \
\_/
return a deep copied graph.
既然是graph的deep copy,那么用bfs就可以了。需要注意的是,如果在bfs的过程中node已经存在,那么直接link上这个node就可以了,重复new node会导致最后的graph中有重复node出现。为了避免这个问题,这里用了一个map去记录所有已经new出来的nodes,如果找到的neighbor刚好在map中存在,那么直接link上就行。
Mycode(AC = 114ms):
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
/**
* @param node: A undirected graph node
* @return: A undirected graph node
*/
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
// write your code here
if (node == NULL) return NULL;
queue<UndirectedGraphNode *> snode;
snode.push(node);
UndirectedGraphNode *root = new UndirectedGraphNode(node->label);
queue<UndirectedGraphNode *> scopy;
scopy.push(root);
map<int, UndirectedGraphNode *> helper;
helper[root->label] = root;
while (!snode.empty()) {
UndirectedGraphNode *n = snode.front();
snode.pop();
UndirectedGraphNode *tmp_n = scopy.front();
scopy.pop();
for (int i = 0; i < n->neighbors.size(); i++) {
// if node already exist, then just link the node
if (helper.find(n->neighbors[i]->label) != helper.end()) {
UndirectedGraphNode *neighbor = helper[n->neighbors[i]->label];
tmp_n->neighbors.push_back(neighbor);
}
else {
// if node doesn't exist, then create the node, and
// push the node into queue
UndirectedGraphNode *neighbor = new UndirectedGraphNode(n->neighbors[i]->label);
tmp_n->neighbors.push_back(neighbor);
helper[neighbor->label] = neighbor;
scopy.push(neighbor);
snode.push(n->neighbors[i]);
}
}
}
return root;
}
};