Clone an undirected graph. Each node in the graph contains a label
and a list of its neighbors
.
OJ's undirected graph serialization:
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 / \ \_/
思路:根据label 从而map来map去。。。先dfs一遍创建节点,再dfs一遍拷贝neighbors.
这道题应该被我做复杂了,写的太复杂,过两天自己都看不懂了。
dm存储的是新建的节点,raw存储的是原图的neighbors信息,map的key都是label
参考代码:
/**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
unordered_map<int, UndirectedGraphNode*>dm;
unordered_map<int, vector<UndirectedGraphNode*>>raw;
void dfs_travel(UndirectedGraphNode *node)
{
if(dm.find(node->label)==dm.end())
{
UndirectedGraphNode* nd = new UndirectedGraphNode(node->label);
dm[node->label] = nd;
raw[node->label] = node->neighbors;
for(int i = 0; i<node->neighbors.size(); ++i)
{
if(dm.find(node->neighbors[i]->label)==dm.end())
dfs_travel(node->neighbors[i]);
}
}
}
void dfs_assign(UndirectedGraphNode *node)
{
if(dm[node->label]->neighbors.empty())
{
for(int i = 0; i<raw[node->label].size(); ++i)
{
dm[node->label]->neighbors.push_back(dm[raw[node->label][i]->label]);
if(dm[node->neighbors[i]->label]->neighbors.empty())
dfs_assign(dm[node->neighbors[i]->label]);
}
}
}
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if(!node)
return node;
dfs_travel(node);
dfs_assign(node);
return dm[node->label];
}
};