problem:
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:
thinking:
(1)要新建圖的各個節(jié)點,保持鄰接關(guān)系不變。
(2)采取unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> 存儲原節(jié)點和新節(jié)點。而不是unordered_map<int, UndirectedGraphNode*>,
效力要高很多
(3)采取BFS思想,將原節(jié)點的鄰接節(jié)點全部入?;蚨褩?,遍歷節(jié)點。
(4)map中查找key是不是存在可以調(diào)用find(),也能夠調(diào)用count(),后者效力更高
(5)提交沒通過,結(jié)果不正確:
Input:{0,1,5#1,2,5#2,3#3,4,4#4,5,5#5}
Output:{0,5,1#1,5,2#2,3#3,4,4#4,5,5#5}
Expected:{0,1,5#1,2,5#2,3#3,4,4#4,5,5#5}
其實,結(jié)果是正確的,由于對無向圖,節(jié)點出現(xiàn)的順序不影響圖的結(jié)構(gòu),只能說這個驗證程序只驗證了1種結(jié)果
code: